66
64

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PHPからPDOを使用してMySQL接続

Last updated at Posted at 2013-05-28

基本的な接続フォーマット

$dns = "mysql:host=127.0.0.1; dbname=db_name;charset=utf8";
$dns_id = "user_id";
$dns_pw = "password";

try {
	// MySQLサーバへ接続
	$pdo = new PDO($dns, $dns_id, $dns_pw, array(PDO::ATTR_EMULATE_PREPARES => false));

	// 処理
	
} catch(PDOException $e){
	var_dump($e->getMessage());
}
// 切断
$pdo = null;

単純なクエリーの実行

// クエリーの実行
$sql = "SELECT id, name, address FROM members";
$statement = $pdo->query($sql);

// 結果の取得
$members = array();
foreach ($statement as $row) {
	$members[] = $row;
}
var_dump($members);

// バージョンによってはきちんとcloseしないと次のSQLが実行されない
$statement->closeCursor();

INSERT/UPDATE/DELETEの実行

// クエリーの実行
$sql = "INSERT INTO any_table (column1, colmn2) VALUES ('apple', 12345) ";
$count = $pdo->exec($sql);

// 戻り値は実行件数。falseが返る可能性もあるので注意
echo $count;

トランザクション ※ MyISAMでは不可

// トランザクション開始
$pdo->beginTransaction();

// INSERTとか DELETEとか

// トランザクション完了
$pdo->commit();

// トランザクション取り消し
$pdo->rollBack();   

PreparedStatement

名前つきプレスホルダにキーワードを指定した接続
bindValue()のかわりにbindParam()でも可。bindParam()はexcute()時に値を評価。

// 準備
$sql = "INSERT INTO any_table (column1, colmn2) VALUES (:val1, :val2) ";
$sth = $pdo->prepare($sql);
$sth->bindValue(':val1', 'apple', PDO::PARAM_STR);
$sth->bindValue(':val2', 12345, PDO::PARAM_INT);

// 実行
$sth->execute();

// 直近の実行結果の行数を得る
$count = $sth->rowCount();
echo $count;

プレスホルダにキーワードを指定した接続

// 準備
$sql = "INSERT INTO any_table (column1, colmn2) VALUES (?, ?) ";
$sth = $pdo->prepare($sql);
$sth-> bindValue(1, 'apple', PDO::PARAM_STR);
$sth-> bindValue(2, 12345, PDO::PARAM_INT);

// 実行
$sth->execute();

// 直近の実行結果の行数を得る
$count = $sth->rowCount();
echo $count;

読込

$sql = "SELECT id, name, address FROM members WHERE id = ?";
$sth = $pdo->prepare($sql);
$sth->bindParam(1, $value, PDO::PARAM_STR); 

$sth->execute();
while ($row = $stmt->fetch()) {
    print_r($row);
}
66
64
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
66
64

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?