Mysql update query with prepared statement is giving error

我与影子孤独终老i 提交于 2019-11-30 09:41:41

问题


I am getting the following error in the code below.

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?


回答1:


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

So, change:

$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'";

to:

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

It's as simple as that.

The manual contains the proper syntax:

  • http://php.net/manual/en/mysqli-stmt.bind-param.php

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);


来源:https://stackoverflow.com/questions/48123286/mysql-update-query-with-prepared-statement-is-giving-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!