INSERT INTO table_name (col1, col2, ...) VALUES (val1, val2, ...);
'value'mysql> USE TUTORIALS;
mysql> INSERT INTO tutorials_tbl (tutorial_title, tutorial_author, submission_date)
-> VALUES ("Learn PHP", "John Poul", NOW());
Query OK, 1 row affected (0.01 sec)
mysql> INSERT INTO tutorials_tbl (tutorial_title, tutorial_author, submission_date)
-> VALUES ("Learn MySQL", "Abdul S", NOW()), ("JAVA Tutorial", "Sanjay", '2007-05-06');
Query OK, 2 rows affected (0.01 sec)
Records: 2 Duplicates: 0 Warnings: 0
技巧:單條 INSERT 可寫多組 VALUES,批量插入效率遠高於多條語句。
<?php
$mysqli = new mysqli('localhost', 'root', 'rootpassword', 'TUTORIALS', 3306);
if ($mysqli->connect_errno) { die('連接失敗: ' . $mysqli->connect_error); }
// 預處理語句,防止 SQL 注入
$stmt = $mysqli->prepare("INSERT INTO tutorials_tbl (tutorial_title, tutorial_author, submission_date) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $title, $author, $date);
// 模擬表單數據
$title = $_POST['tutorial_title'] ?? 'Test Title';
$author = $_POST['tutorial_author'] ?? 'Test Author';
$date = $_POST['submission_date'] ?? date('Y-m-d');
if ($stmt->execute()) {
echo "插入成功,自增 ID: " . $stmt->insert_id;
} else {
echo "插入失敗: " . $stmt->error;
}
$stmt->close();
$mysqli->close();
?>
prepare() + bind_param() 徹底杜絕 SQL 注入。"INSERT ... VALUES ('$title', ...)" 是高危寫法。get_magic_quotes_gpc(),無需手動 addslashes()。$stmt->insert_id 或 $mysqli->insert_id$pdo->lastInsertId()