0

我是 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;

}

?>
4

1 回答 1

0

一个简单的 Prepare 语句类似于

$query = $this->db->prepare("Query here WHERE something = ?")- 请注意,此示例取自我的网站,因此您可能会有其他内容,而不是$this->->prepare.

关键是"= something "被表示为问号。

然后将该问号的值绑定到查询

$query->bindValue(1, passed in parameter)

作为一个完整的工作示例:

    //function to add 1 to downloads each time a file is downloaded
public function addToDownload($filename){

    $query = $this->db->prepare('UPDATE trainingMaterial SET downloads = downloads + 1 WHERE filename = ?');
    $query->bindValue(1, $filename);

    try{

        $query->execute();

    }catch(PDOException $e){
        die($e->getMessage());
    }

}


Your query `$assign = "INSERT INTO contacts(firstName,lastName,email,phone,birthday) VALUES ('$_POST[firstName]','$_POST[lastName]','$_POST[email]','$_POST[phone]','$_POST[birthday]')";

将会

$assign = "INSERT INTO contacts(firstName,lastName,email,phone,birthday) VALUES ?,?,?,?,?)";
$assign->bindValue(1, '$_POST[firstName]')
$assign->bindValue(2, '$_POST[lastName]')

等等等等

于 2013-07-27T02:07:03.703 回答