简体   繁体   中英

PHP, MYSQL Creating a blog comment system

I am currently working on developing a blogging system. For the most part I have the blog done, just creating the scripts to allow users to post comments to each blog. My PHP select code is getting an error along the lines of

check the manual that corresponds to your MySQL server version for the right syntax to use near 'DESC WHERE blogID = 6' at line 1.

The full code of my SQL statement is:

SELECT commentID, blogID FROM blog_comments   
ORDER BY commentID LIMIT 1 DESC WHERE blogID = '.$row['postID'];`

I am aware that this current statement is susceptible to SQL Injections, and have tried using tokens to ensure I am protected from that.

the $row['postiD'] is from a previous SQL statement that was ran to display the actual blog post. This is intended to go on the main page, where I don't need to display the actual comment text, but rather just the number of comments that are on that particular blog. I can post the full code if needed.

Okay, I updated my SQL statement and fixed that issue. However, the page is not displaying the commentID number, and $e is not getting executed, nor do I get any errors in my apache2 log.

$query = "SELECT commentID, blogID FROM blog_comments WHERE blogID ':postid' ORDER BY commentID DESC LIMIT 1";
$query_params = array(':postid' => $row['postID']);
try {
    $stmt = $db->prepare($query);
    $result = $stmt->execute($query_params);
}
catch(PDOException $e)
{
    // dont echo $e on production site
    die($e->getMessage());
}
$rows = $stmt->fetchAll();
?>
<?php foreach($rows as $row): ?>
    <?php echo $row['commentID']; ?>
<?php endforeach; ?>
comments

Move WHERE case just after select:

'SELECT commentID, blogID FROM blog_comments 
 WHERE blogID = '.$row['postID'].' ORDER BY commentID DESC LIMIT 1'

To prevent SQL-injections use PDO and prepared statements : ( http://php.net/manual/en/pdo.prepared-statements.php ).

You really need to learn how we create select ,order, where and limit statement in SQL

Your query would be

"SELECT `commentID`, `blogID` FROM `blog_comments`  WHERE `blogID` = '".$row['postID']."' ORDER BY `commentID` DESC LIMIT 1" ;

Read Tutorial

Also read How can I prevent SQL-injection

你写错了查询

'SELECT commentID, blogID FROM blog_comments WHERE blogID = '.$row['postID'].' ORDER BY commentID DESC LIMIT 1';

Your query elements sequence seems wrong , Please follow below query sequence :

'SELECT commentID, blogID FROM blog_comments WHERE blogID = '.$row['postID'].' ORDER BY commentID DESC LIMIT 1';

Require to set ORDER BY & LIMIT after WHERE clause.

SELECT `commentID`, `blogID` FROM `blog_comments` WHERE blogID = $row['postID'] order by `commentID` DESC limit 1

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