PHP 連線MySQL 資料庫需七步驟:建立連線(msiql_connect())準備查詢(mysqli_prepare())綁定參數(mysqli_stmt_bind_param())執行查詢(mysqli_stmt_execute())取得結果(my_stmt_get_result(mysqli_stmt_execute())取得結果(my_stmt_get_result(mysqli_stmt mysqli_fetch_assoc())關閉連線(mysqli_close())
#PHP 資料庫連線所需的步驟,從基礎到進階
1. 基礎連線
使用mysqli_connect() 函數建立與MySQL 資料庫的連線:
$mysqli = mysqli_connect("localhost", "username", "password", "database"); if (!$mysqli) { echo "Unable to connect to the database: " . mysqli_connect_error(); exit(); }
2. 準備查詢
使用mysqli_prepare() 函數準備一個查詢:
$stmt = $mysqli->prepare("SELECT * FROM users WHERE id = ?");
3. 綁定參數
使用mysqli_stmt_bind_param() 函數綁定查詢中的參數:
$param = 3; mysqli_stmt_bind_param($stmt, "i", $param);
4. 執行查詢
使用mysqli_stmt_execute() 函數執行查詢:
mysqli_stmt_execute($stmt);
5. 取得結果
#使用mysqli_stmt_get_result() 函數取得查詢結果:
$result = mysqli_stmt_get_result($stmt);
6.遍歷結果
使用mysqli_fetch_assoc() 函數遍歷查詢結果:
while ($row = mysqli_fetch_assoc($result)) { echo "ID: " . $row['id'] . "<br>"; echo "Name: " . $row['name'] . "<br>"; }
7. 關閉連線
使用mysqli_close() 函數關閉與資料庫的連線:
mysqli_close($mysqli);
實戰案例
###連接到資料庫並查詢用戶######$mysqli = mysqli_connect("localhost", "username", "password", "database"); if (!$mysqli) { echo "Unable to connect to the database: " . mysqli_connect_error(); exit(); } $stmt = $mysqli->prepare("SELECT * FROM users WHERE id = ?"); mysqli_stmt_bind_param($stmt, "i", $param); mysqli_stmt_execute($stmt); $result = mysqli_stmt_get_result($stmt); while ($row = mysqli_fetch_assoc($result)) { echo "ID: " . $row['id'] . "<br>"; echo "Name: " . $row['name'] . "<br>"; } mysqli_close($mysqli);
以上是PHP資料庫連線所需的步驟,從基礎到進階的詳細內容。更多資訊請關注PHP中文網其他相關文章!