MySQL寫入數據庫代碼詳解
連接到MySQL數據庫
在使用MySQL之前,首先需要連接到MySQL數據庫。我們可以使用PHP的mysqli擴展來連接到MySQL數據庫。以下是連接到MySQL數據庫的樣板代碼:
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// 創建connection
$conn = new mysqli($servername, $username, $password, $dbname);
// 檢查connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
插入數據到數據庫
當您有了連接對象之后,就可以開始向數據庫中插入數據了。以下是向MySQL數據庫中插入數據的樣板代碼:
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "
" . $conn->error;
}
準備語句
當您使用用戶提供的數據來構造數據庫查詢時,您需要使用準備語句。準備語句能夠防止SQL注入攻擊。以下是準備語句的樣板代碼:
//準備statement和綁定參數
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);
//設置參數并執行
$firstname = "John";
$lastname = "Doe";
$email = "john@example.com";
$stmt->execute();
echo "New records created successfully";
最后,不要忘記關閉MySQL數據庫連接:
//關閉連接
$conn->close();