我是 PHP 新手,创建了一个简单的 php 站点,允许我提交表单并删除存储在数据库中的数据。有人告诉我最好使用准备好的语句来避免 SQL 注入。
我更新了我的删除,它仍然有效,不确定它是否完全正确:
<?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;
}
?>