php准备好的语句(INSERT不起作用)

时间:2019-04-28 09:55:53

标签: php mysql sql mysqli pdo

我正在尝试使用准备好的stmt以避免SQL注入,但它无法正常工作。我已经用一些警报语句包围了我的代码,以了解问题出在哪里。它位于bind_param语句中。之后的一切都永远不会执行。希望我能找到帮助!

到目前为止,过去3个小时一直没有找到答案。 P.S表有6列。一个ID会自动递增,其余的就是您可以从代码中看到的

$db = new PDO("mysql:port=3302;dbname=thedoctors", "root", ""); 
$Data = $_POST["post"];
$postData = $db->quote($_POST["post"]); //user's post
$user = $db->quote($_SESSION["user"]);    //user's email
$stmt = $db->prepare("INSERT INTO post (body,timee,likes,comments,userem) VALUES (?, NOW(), ?, ?, ?);");

// set parameters and execute

$first = ".$postData.";
$like = 0;
$comment = 0;

$stmt->bind_param("siis", $first, $like, $comment, $user);
echo "<script>alert('hello');</script>";
// $result = $stmt->get_result();
// header("location:activity.php");
if (strlen($Data) > 3000 || strlen($Data) < 1) {
    echo "<script>alert('Make sure your post is of correct length!');</script>";
} else {
    $stmt->execute();
    echo "<script>alert('Post uploaded! You can check it in your profile!');</script>";
}

1 个答案:

答案 0 :(得分:1)

由于您使用的不是PDO mysqli接口,因此需要在SQL查询中使用命名参数,如此处所述: https://www.php.net/manual/en/pdo.prepare.php

当前,您依赖于mysqli接口上的方法bind_param。

基于PDO文档:

<?php
/* Execute a prepared statement by passing an array of values */
$sql = 'SELECT name, colour, calories
    FROM fruit
    WHERE calories < :calories AND colour = :colour';
$sth = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute(array(':calories' => 150, ':colour' => 'red'));
$red = $sth->fetchAll();
$sth->execute(array(':calories' => 175, ':colour' => 'yellow'));
$yellow = $sth->fetchAll();
?>

另外,我建议使用bindValue来更明确地说明您正在为占位符设置一些值,如下所示:

<?php
/* Execute a prepared statement by binding PHP variables */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < :calories AND colour = :colour');
$sth->bindValue(':calories', $calories, PDO::PARAM_INT);
$sth->bindValue(':colour', $colour, PDO::PARAM_STR);
$sth->execute();
?>