so I know this is a frequently asked question on stackoverflow but I'm tearing my hair out trying to get this to work. I'm currently building a blogging site and with it I'm trying to develop a real-time notification system with AJAX following an online tutorial. The AJAX code and everything else works, but the SQL used in the tutorial doesn't make use of prepared statements and I'm unsure on how to edit the code to make use of prepared statements. Below is a copy of the code itself:
$query = "SELECT tblblogpost.heading
FROM tblblogpost, tblconfirmedposts, tbluser
WHERE tblblogpost.postID=tblconfirmedposts.postID
AND tblblogpost.userID=tbluser.userID
AND tbluser.userID=$uID
AND tblconfirmedposts.confirmed=1
AND tbluser.position=1
ORDER By tblblogpost.postDate DESC LIMIT 10";
$result = mysqli_query($mysqli, $query);
$output = '';
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
$output .= '
<li>
<a href="#">
<strong>'.$row["comment_title"].'</strong><br />
</a>
</li>
';
}
}
else{
$output .= '<li><a href="#" class="text-bold text-italic">No Notifications Available</a></li>';
}
What I have tried so far, is to re-write the entire query using mysqli_prepare
and making use of mysqli_stmt_bind_param
to bind the parameters. However, this has not worked. If needed I can post a copy of what I tried using mysqli_prepare
.
This code does work well, but I dislike that I have variables inside of my SQL string, I'd much prefer to use prepared statements. If I can have a bit of assistance in just the re-writing aspect, I would be very much grateful.
Also, I do understand that my SQL statement is messy. I'm not very well versed in it, but for what I'm doing the query works fine. I would really like to focus on trying to rewrite the code to make use of prepared statements so that I can replace the $uID with a "?" and bind the variable instead.
$query = "SELECT tblblogpost.heading
FROM tblblogpost, tblconfirmedposts, tbluser
WHERE tblblogpost.postID=tblconfirmedposts.postID
AND tblblogpost.userID=tbluser.userID
AND tbluser.userID=?
AND tblconfirmedposts.confirmed=1
AND tbluser.position=1
ORDER By tblblogpost.postDate DESC LIMIT 10";
if($stmt=mysqli_prepare($mysqli, $query)){
//bind post ID for the query
//mysqli_stmt_bind_param($stmt, "i", $uID);
//execute query
mysqli_stmt_execute($stmt);
//get results
$result=mysqli_stmt_get_result($stmt);
while($row=mysqli_fetch_array($result))
{
$output .= '
<li>
<a href="#">
<strong>'.$row["heading"].'</strong><br />
</a>
</li>
';
}//end of while loop
}//end of stmt