php - 如何重写此 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
解决方案
推荐阅读
- laravel - 如果两个外键匹配,如何在多对多关系中找到速率?
- r - 通过闪亮的应用程序运行 bat 文件时的进度条
- python - 如何检测两个盒子是否相互连接?
- sql - Presto SQL + Athena:投射日期失败并出现错误消息:INVALID_FUNCTION_ARGUMENT
- node.js - 使用多个条件 dynamodb 过滤数据
- python - Python Selenium Webdriver 等待轮询频率
- firebase - 我想将我的 Firebase 信息与我的邮件联系起来
- python - 如何访问 request.get().json() 响应中的深层嵌套键?
- tensorflow - 从检查点可视化 TensorFlow Graph
- python - 如何对第 1 列中具有相同值的两个或多个 csv 文件的行求和?