Last active
November 23, 2016 00:43
-
-
Save taitokiss/3c54cc49aacc5bf906213bd9771658b7 to your computer and use it in GitHub Desktop.
mysqli_系 データベースへの接続サンプル6(オブジェクト型でプリペアドステートメントを使う
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// mysqliクラスのオブジェクトを作成 | |
$mysqli = new mysqli("localhost", "testuser", "testuser", "uriage"); | |
if ($mysqli->connect_error) { // connect_errorはPHP5.3.0以降で有効 | |
die("connect_error" . $mysqli->connect_error); | |
} | |
// 文字化け防止 | |
$mysqli->set_charset("utf8"); | |
// ?(パラメータマーカ)を用いたSELECT文のひな型をセット | |
$sql = "SELECT id, name FROM shouhin WHERE id > ? AND id < ?"; | |
// ステートメントハンドルを取得する | |
if ($stmt = $mysqli->prepare($sql)) { | |
$id1 = 2; $id2 = 5; // 次のbind_param()行と前後しても良い | |
// 条件値をSQLにバインドする | |
$stmt->bind_param("ii", $id1, $id2); | |
// プリペアドステートメントを実行 | |
$stmt->execute(); | |
// 取得結果を変数にバインドする | |
$stmt->bind_result($id, $name); | |
// 値を取得 | |
while ($stmt->fetch()) { | |
echo "id=$id, name=$name<br>"; | |
} | |
// ステートメントを閉じる | |
$stmt->close(); | |
} | |
// DB接続を閉じる | |
$mysqli->close(); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment