1.SQL查詢(SELECT):
<?php
$servername = "localhost"; // MySQL服務(wù)器名稱或IP地址
$username = "root"; // MySQL用戶名
$password = ""; // MySQL密碼
$dbname = "myDB"; // 要連接的數(shù)據(jù)庫名稱
// 創(chuàng)建與MySQL數(shù)據(jù)庫的連接
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// 編寫SQL查詢語句
$sql = "SELECT * FROM myTable";
// 執(zhí)行查詢并獲取結(jié)果集
$result = $conn->query($sql);
// 處理結(jié)果集
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"]. ", Name: " . $row["name"]. "<br>";
}
} else {
echo "No results found.";
}
// 關(guān)閉數(shù)據(jù)庫連接
$conn->close();
?>
2.SQL插入(INSERT):
<?php
$servername = "localhost"; // MySQL服務(wù)器名稱或IP地址
$username = "root"; // MySQL用戶名
$password = ""; // MySQL密碼
$dbname = "myDB"; // 要連接的數(shù)據(jù)庫名稱
// 創(chuàng)建與MySQL數(shù)據(jù)庫的連接
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// 編寫SQL插入語句
$sql = "INSERT INTO myTable (name, age) VALUES ('John', '30')";
// 執(zhí)行插入操作
if ($conn->query($sql) === TRUE) {
echo "New record created successfully!";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
// 關(guān)閉數(shù)據(jù)庫連接
$conn->close();
?>
3.SQL更新(UPDATE):
<?php
$servername = "localhost"; // MySQL服務(wù)器名稱或IP地址
$username = "root"; // MySQL用戶名
$password = ""; // MySQL密碼
$dbname = "myDB"; // 要連接的數(shù)據(jù)庫名稱
// 創(chuàng)建與MySQL數(shù)據(jù)庫的連接
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// 編寫SQL更新語句
$sql = "UPDATE myTable SET name='Jane' WHERE id=1";
// 執(zhí)行更新操作
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully!";
} else {
echo "Error updating record: " . $conn->error;
}
// 關(guān)閉數(shù)據(jù)庫連接
$conn->close();
?>
4.SQL刪除(DELETE):
<?php
$servername = "localhost"; // 數(shù)據(jù)庫服務(wù)器名稱
$username = "your_username"; // 數(shù)據(jù)庫用戶名
$password = "your_password"; // 數(shù)據(jù)庫密碼
$dbname = "your_database"; // 數(shù)據(jù)庫名稱
// 創(chuàng)建與數(shù)據(jù)庫的連接
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//編寫SQL語句來執(zhí)行刪除操作斥黑。根據(jù)需求選擇合適的條件來指定要刪除的記錄。
//your_table應(yīng)該被替換為要從其中刪除記錄的表格名稱,
//而condition則是指定要刪除的記錄的條件。
$sql = "DELETE FROM your_table WHERE condition";
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully.";
} else {
echo "Error deleting record: " . $conn->error;
}
//最后惨远,斷開與數(shù)據(jù)庫的連接。
$conn->close();
?>