带准备语句的MySQL更新查询给出错误

问题描述:

我在下面的代码中遇到以下错误.

I am getting the following error in the code below.

警告:mysqli_stmt :: bind_param():第39行的C:\ wamp \ www \ purev \ admin \ edit.php中准备好的语句中的变量数量与参数数量不匹配

Warning: mysqli_stmt::bind_param(): Number of variables doesn't match number of parameters in prepared statement in C:\wamp\www\purev\admin\edit.php on line 39

if(isset($_POST['submit'])){
    $post_title = $_POST['posttitle'];
    $content = $_POST['content'];
    $author_name = $_POST['authorname'];
    $category = $_POST['category'];
    $post_date = $_POST['postdate'];

    if(isset($_FILES['image']['name']) && ($_FILES['image']['name'] !="")){
        $size=$_FILES['image']['size'];
        $temp=$_FILES['image']['tmp_name'];
        $type=$_FILES['image']['type'];
        $image_name=$_FILES['image']['name'];
        unlink("../images/"."$image_name");

        move_uploaded_file($temp,"../images/$image_name");
    }

//-------------------UPDATE POST------------------------

    $sql = 
        "UPDATE blog_posts 
            SET post_title='$post_title', 
            content='$content', 
            author_name='$author_name', 
            category='$category', 
            post_date='$post_date',
            image='$image_name'
            WHERE post_id='$id'";

    $stmt = $con->prepare($sql);

    $stmt->bind_param("sssssii", $post_title, $content, $author_name, $category, $image_name, $post_date, $id);
    $stmt->execute();

在不使用预准备语句的情况下,查询有效.您有任何解决办法的想法吗?

Without using prepared statement the query works. Do you have any any ideas how to solve this?

有人在评论中说过,您错过了占位符.

It's been said in comments, you missed the placeholders.

因此,更改:

$sql = 
    "UPDATE blog_posts 
        SET post_title='$post_title', 
        content='$content', 
        author_name='$author_name', 
        category='$category', 
        post_date='$post_date',
        image='$image_name'
        WHERE post_id='$id'";

收件人:

$sql = 
    "UPDATE blog_posts 
        SET post_title=?, 
        content=?, 
        author_name=?, 
        category=?, 
        post_date=?, 
        image=? 
        WHERE post_id=?";

就这么简单.

手册包含正确的语法:

别忘了以正确的顺序传递参数.它们的传递顺序应与查询中使用的顺序相同(您将图像替换为发布日期),因此应为:

Don't forget to pass the arguments in the correct order. They should be passed in the same order as they are used in the query (you swapped the image with post date), so it should be:

$stmt->bind_param("ssssisi", $post_title, $content, $author_name, $category, $post_date, $image_name, $id);