首页 > 解决方案 > 如何重写此 PHP-MySQL 代码以接受准备好的语句?

问题描述

所以我知道这是关于 stackoverflow 的一个常见问题,但我正在努力让它发挥作用。我目前正在构建一个博客站点,并尝试通过在线教程使用 AJAX 开发一个实时通知系统。AJAX 代码和其他一切都有效,但本教程中使用的 SQL 没有使用准备好的语句,我不确定如何编辑代码以使用准备好的语句。以下是代码本身的副本:

$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>';
}

到目前为止,我尝试过的是使用mysqli_prepare和利用mysqli_stmt_bind_param绑定参数来重写整个查询。然而,这并没有奏效。如果需要,我可以发布我尝试使用的副本mysqli_prepare

这段代码运行良好,但我不喜欢我的 SQL 字符串中有变量,我更喜欢使用准备好的语句。如果我能在重写方面得到一点帮助,我将非常感激。

另外,我知道我的 SQL 语句很混乱。我不是很精通它,但是对于我正在做的事情,查询工作正常。我真的很想专注于尝试重写代码以使用准备好的语句,以便我可以将 $uID 替换为“?” 并改为绑定变量。

$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

标签: phpmysqli

解决方案


推荐阅读