Mysql update query with prepared statement is givi

2019-01-29 04:45发布

问题:

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