PHP MySQL在预准备语句中围绕匿名变量抛出错误

时间:2016-01-04 21:00:22

标签: php mysql prepared-statement

当我运行我准备好的语句时,我收到以下错误:

  

错误:INSERT INTO文章(urlheadlinepubDatesourceimage_loc)VALUES(?,?,?,?,? )   您的SQL语法有错误;查看与MySQL服务器版本对应的手册,以便在第6行“?,?,?,?,?)”附近使用正确的语法

这是似乎抛出错误的代码:

            $sql = "INSERT INTO $tableName (`url`, 
                            `headline`, 
                            `pubDate`, 
                            `source`, 
                            `image_loc`) 
                VALUES(?, ?, ?, ?, ?)";

        // MySQLi connection, binds variables to prevent injection, executes
        $stmt = $connection->prepare($sql);
        $stmt->bind_param('sssss', $url, $headline, $pubDate, $source, $image_loc);
        $stmt->execute();

编辑:这是我在单独的文件中设置为连接的内容。它起作用的意义是一切都被保存了......我只是在抛出一个错误。

$servername = "localhost";
$username = "xxxxxx";
$password = "xxxxxx";
$dbname = "news";
$tableName = "articles";

$connection = mysqli_connect($servername, $username, $password, $dbname);

if (!$connection) {
  die("Connection failed: " . mysqli_connect_error());
}

再次编辑:这是用于检查插入成功的代码,虽然我猜这可能是问题的根源(但我没有足够的经验来理解为什么):< / p>

if (mysqli_query($connection, $sql)) {
            echo "New record created successfully";
        } else {
            echo "Error: " . $sql . "<br>" . mysqli_error($connection) . "<br>";
        }

2 个答案:

答案 0 :(得分:5)

您的代码:

if (mysqli_query($connection, $sql)) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . mysqli_error($connection) . "<br>";
}

...使用mysqli_query()。这实际上是执行查询的另一种方式,只是与execute()不同,它不使用绑定参数。它只是将查询发送到数据库,问号和所有内容,从而产生错误。

如果要检查错误,则应在运行时检查execute()语句的结果,而不是执行进一步的查询。将$stmt->execute()行替换为类似的内容,以执行查询并测试成功:

if ($stmt->execute()) {
    // Success
} else {
    // Failure
}

答案 1 :(得分:1)

而不是

if (mysqli_query($connection, $sql)) {
        echo "New record created successfully";
} else {
        echo "Error: " . $sql . "<br>" . mysqli_error($connection) . "<br>";
}

你应该使用mysqli::$affected_rows属性,像这样;

if ($connection->affected_rows > 0) {
        echo "New record created successfully";
} else {
        echo "Error: " . $sql . "<br>" . $connection->error() . "<br>";
}