您好,登錄后才能下訂單哦!
在PHP中操作MySQL臨時表,可以有效地存儲和操作中間結果
CREATE TEMPORARY TABLE
語句創建臨時表。臨時表在數據庫會話結束時自動刪除。例如,創建一個名為temp_table
的臨時表:$conn = new mysqli($servername, $username, $password, $dbname);
// 檢查連接
if ($conn->connect_error) {
die("連接失敗: " . $conn->connect_error);
}
$sql = "CREATE TEMPORARY TABLE temp_table (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(30),
age INT(3)
)";
if ($conn->query($sql) === TRUE) {
echo "臨時表 temp_table 創建成功";
} else {
echo "創建臨時表錯誤: " . $conn->error;
}
$conn->close();
INSERT INTO
語句將數據插入到臨時表中。例如,向temp_table
插入數據:$conn = new mysqli($servername, $username, $password, $dbname);
// 檢查連接
if ($conn->connect_error) {
die("連接失敗: " . $conn->connect_error);
}
$sql = "INSERT INTO temp_table (name, age)
VALUES ('John', 25),
('Jane', 30),
('Mike', 35)";
if ($conn->query($sql) === TRUE) {
echo "數據插入成功";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
SELECT
語句查詢臨時表中的數據。例如,從temp_table
查詢數據:$conn = new mysqli($servername, $username, $password, $dbname);
// 檢查連接
if ($conn->connect_error) {
die("連接失敗: " . $conn->connect_error);
}
$sql = "SELECT * FROM temp_table";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// 輸出數據
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. " - Age: " . $row["age"]. "<br>";
}
} else {
echo "0 結果";
}
$conn->close();
UPDATE
語句更新臨時表中的數據。例如,更新temp_table
中的年齡:$conn = new mysqli($servername, $username, $password, $dbname);
// 檢查連接
if ($conn->connect_error) {
die("連接失敗: " . $conn->connect_error);
}
$sql = "UPDATE temp_table
SET age = age + 1
WHERE name = 'John'";
if ($conn->query($sql) === TRUE) {
echo "年齡更新成功";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
DELETE
語句刪除臨時表中的數據。例如,從temp_table
刪除數據:$conn = new mysqli($servername, $username, $password, $dbname);
// 檢查連接
if ($conn->connect_error) {
die("連接失敗: " . $conn->connect_error);
}
$sql = "DELETE FROM temp_table WHERE name = 'John'";
if ($conn->query($sql) === TRUE) {
echo "數據刪除成功";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
DROP TEMPORARY TABLE
語句刪除臨時表。例如,刪除temp_table
:$conn = new mysqli($servername, $username, $password, $dbname);
// 檢查連接
if ($conn->connect_error) {
die("連接失敗: " . $conn->connect_error);
}
$sql = "DROP TEMPORARY TABLE temp_table";
if ($conn->query($sql) === TRUE) {
echo "臨時表 temp_table 刪除成功";
} else {
echo "刪除臨時表錯誤: " . $conn->error;
}
$conn->close();
總之,在PHP中操作MySQL臨時表時,需要注意創建、插入、查詢、更新、刪除等操作,并確保在使用完臨時表后將其刪除以避免不必要的資源浪費。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。