简体   繁体   中英

UPDATE prepared statement PHP Error

I am creating a dynamic page which changes depending on which ever post the user clicks onto. I am also wanting the views (hit-counter) the page gets to go up by one each time the page is loaded. I am currently getting the following error.

Fatal error: Call to a member function bind_param() on a non-object in C:\\Users\\PC\\Documents\\XAMPP\\htdocs\\post.php on line 13

<?php
session_start();
include 'php/config.php';
$post = $_GET['post'];
$stmt = $mysqli->prepare("SELECT * FROM forum WHERE ForumId = '$post'");
$stmt->execute();
$stmt->bind_result($ForumId,$ForumTitle,$ForumPostText,$PostDate,$Views);
$stmt->fetch();
$stmt->close();

$Views = 1;
$stmt = $mysqli->prepare("UPDATE 'forum' SET 'Views' = 'Views'+ 1 WHERE 'ForumId' = '?' ");
$stmt->bind_param('i',$post);
$stmt->execute();
$stmt->close();


?>  
<!DOCTYPE html>
// The rest of the webpage yada yada yada

Remove ( ' ) single quotes in update query and use backtick (`) instead

So

"UPDATE `forum` SET `Views` = Views+ 1 WHERE `ForumId` = ?"

Although Krish R's response is the solution, one of the things you will want to do in cases like this, is look at $mysqli->error to actually get an error message. This will tell you that you have a syntax error near 'forum' SET 'Vi... . That in itself should indicate that that specific character (the first ' in the string) is the most likely cause of the error.

It seems you have a problem in the query.

Take note, that PDO statement dont need single quotes

Try with this:

$stmt = $mysqli->prepare("UPDATE forum SET Views = Views+ 1 WHERE ForumId = ?");
$stmt->bind_param('i', $post);
<?php
session_start();
include 'php/config.php';
$post = $_GET['post'];
$stmt = $mysqli->prepare("SELECT * FROM forum WHERE ForumId = $post");
$stmt->execute();
$stmt->bind_result($ForumId,$ForumTitle,$ForumPostText,$PostDate,$Views);
$stmt->fetch();
$stmt->close();

$Views = 1;
$stmt = $mysqli->prepare("UPDATE forum SET Views = Views + 1 WHERE ForumId = ?");
$stmt->bind_param('i', $post);
$stmt->execute();
$stmt->close();


?>  
<!DOCTYPE html>

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