連接數(shù)據(jù)庫(kù)
$servername = "localhost"; $username = "root"; $password = "password"; $dbname = "myDB"; $conn = mysqli_connect($servername, $username, $password, $dbname);
檢查連接是否成功
if (!$conn) { die("連接失敗: " . mysqli_connect_error()); }
查詢數(shù)據(jù)
$sql = "SELECT id, firstname, lastname FROM MyGuests"; $result = mysqli_query($conn, $sql);
輸出查詢結(jié)果
if (mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_assoc($result)) { echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>"; } } else { echo "0 結(jié)果"; }
插入數(shù)據(jù)
$sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com')"; if (mysqli_query($conn, $sql)) { echo "新記錄插入成功"; } else { echo "Error: " . $sql . "<br>" . mysqli_error($conn); }
更新數(shù)據(jù)
$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2"; if (mysqli_query($conn, $sql)) { echo "記錄更新成功"; } else { echo "Error: " . $sql . "<br>" . mysqli_error($conn); }
刪除數(shù)據(jù)
$sql = "DELETE FROM MyGuests WHERE id=3"; if (mysqli_query($conn, $sql)) { echo "記錄刪除成功"; } else { echo "Error: " . $sql . "<br>" . mysqli_error($conn); }
關(guān)閉連接
mysqli_close($conn);
安整的PHP代碼
<?php // 連接數(shù)據(jù)庫(kù) $servername = "localhost"; $username = "root"; $password = "password"; $dbname = "myDB"; $conn = mysqli_connect($servername, $username, $password, $dbname); // 檢查連接是否成功 if (!$conn) { die("連接失敗: " . mysqli_connect_error()); } // 查詢數(shù)據(jù) $sql = "SELECT id, firstname, lastname FROM MyGuests"; $result = mysqli_query($conn, $sql); // 輸出查詢結(jié)果 if (mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_assoc($result)) { echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>"; } } else { echo "0 結(jié)果"; } // 插入數(shù)據(jù) $sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com')"; if (mysqli_query($conn, $sql)) { echo "新記錄插入成功"; } else { echo "Error: " . $sql . "<br>" . mysqli_error($conn); } // 更新數(shù)據(jù) $sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2"; if (mysqli_query($conn, $sql)) { echo "記錄更新成功"; } else { echo "Error: " . $sql . "<br>" . mysqli_error($conn); } // 刪除數(shù)據(jù) $sql = "DELETE FROM MyGuests WHERE id=3"; if (mysqli_query($conn, $sql)) { echo "記錄刪除成功"; } else { echo "Error: " . $sql . "<br>" . mysqli_error($conn); } // 關(guān)閉連接 mysqli_close($conn); ?>
版權(quán)聲明:文章圖片資源來(lái)源于網(wǎng)絡(luò),如有侵權(quán),請(qǐng)留言刪除!!!
評(píng)論