溫馨提示×

php如何操作mysql數(shù)據(jù)庫

小億
81
2024-11-10 09:03:26
欄目: 云計算

要使用PHP操作MySQL數(shù)據(jù)庫,您需要遵循以下步驟:

  1. 連接到MySQL服務(wù)器 要連接到MySQL服務(wù)器,您需要使用PHP的mysqliPDO擴展。以下是使用這兩種擴展的示例代碼:

使用mysqli擴展:

$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";

// 創(chuàng)建連接
$conn = new mysqli($servername, $username, $password, $dbname);

// 檢查連接
if ($conn->connect_error) {
    die("連接失敗: " . $conn->connect_error);
}

使用PDO擴展:

$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // 設(shè)置 PDO 錯誤模式為異常
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    echo "連接失敗: " . $e->getMessage();
}
  1. 執(zhí)行SQL查詢 連接到數(shù)據(jù)庫后,您可以執(zhí)行SQL查詢以檢索、插入、更新或刪除數(shù)據(jù)。以下是執(zhí)行這些操作的示例代碼:

檢索數(shù)據(jù)(SELECT):

$sql = "SELECT * FROM your_table";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // 輸出數(shù)據(jù)
    while($row = $result->fetch_assoc()) {
        echo "id: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
    }
} else {
    echo "0 結(jié)果";
}

插入數(shù)據(jù)(INSERT):

$sql = "INSERT INTO your_table (name, age) VALUES ('John Doe', 30)";
if ($conn->query($sql) === TRUE) {
    echo "新記錄插入成功";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

更新數(shù)據(jù)(UPDATE):

$sql = "UPDATE your_table SET name='Jane Doe' WHERE id=1";
if ($conn->query($sql) === TRUE) {
    echo "更新成功";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

刪除數(shù)據(jù)(DELETE):

$sql = "DELETE FROM your_table WHERE id=1";
if ($conn->query($sql) === TRUE) {
    echo "刪除成功";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}
  1. 關(guān)閉連接 完成數(shù)據(jù)庫操作后,確保關(guān)閉與MySQL服務(wù)器的連接。

使用mysqli擴展關(guān)閉連接:

$conn->close();

使用PDO擴展關(guān)閉連接:

$conn = null;

這就是使用PHP操作MySQL數(shù)據(jù)庫的基本方法。請根據(jù)您的需求調(diào)整代碼示例。

0