简体   繁体   中英

Mysql update query with prepared statement is giving error

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?

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:


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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM