在PHP中實現與MySQL數據庫的連接可以使用以下步驟:
使用mysqli擴展連接MySQL數據庫的示例代碼如下:
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
// 創建連接
$conn = new mysqli($servername, $username, $password, $dbname);
// 檢查連接是否成功
if ($conn->connect_error) {
die("連接失敗: " . $conn->connect_error);
}
echo "連接成功";
使用PDO擴展連接MySQL數據庫的示例代碼如下:
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// 設置 PDO 錯誤模式為異常
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "連接成功";
} catch(PDOException $e) {
echo "連接失敗: " . $e->getMessage();
}
使用mysqli擴展執行查詢語句的示例代碼如下:
$sql = "SELECT * FROM table_name";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// 輸出數據
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 結果";
}
$conn->close();
使用PDO擴展執行查詢語句的示例代碼如下:
$sql = "SELECT * FROM table_name";
$stmt = $conn->query($sql);
if ($stmt->rowCount() > 0) {
// 輸出數據
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 結果";
}
$conn = null;
以上是實現在PHP中與MySQL數據庫連接的基本步驟,您可以根據具體需求進一步擴展和優化代碼。