我是PHP新手,做了一個簡單的php網站,允許我提交表單並刪除存儲在數據庫中的數據。我被告知最好使用預準備語句來避免SQL注入。從mysqli_query到mysqli_prepare出現問題
我更新了我刪除,它仍然有效,不知道是否是完全正確的:
<?php
include("dbconnect.php");
$getid = $_GET["id"];
$delete = mysqli_prepare($database,"DELETE FROM contacts WHERE id IN ($getid)");
mysqli_stmt_execute($delete);
header("Location:http://localhost/address-book");
exit;
?>
但我似乎無法得到添加到數據庫功能正常工作。我嘗試了各種不同的方式來編寫它,但我確信我錯過了一些簡單的東西。下面是我原來寫的不安全的代碼:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
include("inc/dbconnect.php");
// assigns form data to table columns
$assign = "INSERT INTO contacts(firstName,lastName,email,phone,birthday) VALUES ('$_POST[firstName]','$_POST[lastName]','$_POST[email]','$_POST[phone]','$_POST[birthday]')";
//execute query
if (mysqli_query($database,$assign)) {
header("Location:http://localhost/address-book/");
exit;
} else {
exit;
}
?>
如果有人能指導我在正確的方向,我會心存感激。我對這一切都很陌生。
更新:我已經更新了我原來的代碼以及與此上來,而不是進行刪除:
<?php
include("dbconnect.php");
$getid = $_GET["id"];
$delete = mysqli_prepare($database,"DELETE FROM contacts WHERE id IN (?)");
mysqli_stmt_bind_param($delete, 's', $getid);
mysqli_stmt_execute($delete);
header("Location:http://localhost/address-book");
exit;
?>
和附加功能:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
include("inc/dbconnect.php");
$firstName = "$_POST[firstName]";
$lastName = "$_POST[lastName]";
$email = "$_POST[email]";
$phone = "$_POST[phone]";
// assigns form data to table columns
$assign = mysqli_prepare($database,"INSERT INTO contacts(firstName,lastName,email,phone) VALUES (?,?,?,?)");
mysqli_stmt_bind_param($assign, 'ssss', $firstName, $lastName, $email, $phone);
mysqli_stmt_execute($assign);
exit;
}
?>
你不應該使用placeho嗎? lders [(?)](http://php.net/manual/en/mysqli.prepare.php) –