PHP更新不会更新

时间:2014-11-17 01:17:55

标签: php

查询在mysql中运行,提交时没有捕获,但数据没有更新。对于为什么这不起作用甚至如何调试它有什么建议吗?

<?php
if( $_SERVER['REQUEST_METHOD'] == "POST" )  
{
    // var_dump($_POST["first_name"]);
    try
    {

        // this needs to be a lot more secure! 
        // read PDO manual
        $id = $_GET['id'];

        // $description     = $_POST["description"];
        $first_name = $_POST["first_name"];
        $last_name  = $_POST["last_name"];
        $description = $_POST["description"];

        $sql = $db->prepare("UPDATE `exhibitors` SET first_name = '$first_name' WHERE id = '52'");


        $update = $db->query($sql);
    }
    catch ( Exception $e )
    {
        echo " Data could not be updated from the database.";
    }
}

和连接:

<?php
    try
    {
        $db = new PDO("mysql:host=localhost;dbname=openstudios;port=8889","root","root");
        $db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
        $db->exec("SET NAMES 'utf8'");
        // var_dump($db);
    }
    catch ( Exception $e )
    {
        echo "Could not connect to the database.";
        exit;
    }

2 个答案:

答案 0 :(得分:3)

您未在此处正确使用prepare()(或query())。 prepare()用于创建使用execute()运行的“预准备语句”,query()用于运行SQL查询字符串。

不要 将您的$_POST值连接到查询字符串中,这就是您打开SQL注入的方式。您忽略了使用预准备语句的整点

这是针对MySQLi:

$id = $_GET['id'];

// $description = $_POST["description"];
$first_name = $_POST["first_name"];
$last_name  = $_POST["last_name"];
$description = $_POST["description"];

$sql = $db->prepare("UPDATE `exhibitors` SET first_name = ? WHERE id = ?");
$sql->bind_param('sd', $first_name, $id);

$sql->execute();

请参阅文档:http://php.net/manual/en/mysqli.prepare.php

如果您使用的是PDO,则语法略有不同

$id = $_GET['id'];

// $description = $_POST["description"];
$first_name = $_POST["first_name"];
$last_name  = $_POST["last_name"];
$description = $_POST["description"];

$sql = $db->prepare("UPDATE `exhibitors` SET first_name = :first_name WHERE id = :id");

$sql->execute(array(
    'first_name' => $first_name,
    'id' => $id
));

答案 1 :(得分:2)

对于准备好的陈述,你应该使用类似的东西

$sql = $db->prepare('UPDATE exhibitors SET first_name = :first_name WHERE id = :id');
$sql->execute(array('first_name' => $first_name,'id' => 52));

如果您只想使用查询语句,(哪一个不应该接受SQL注入)

$db->query("UPDATE exhibitors SET first_name = '$first_name' WHERE id = 52");