php - MySQL - 将部分查询加入新查询?
问题描述
我有以下查询表格的代码。然后它使用结果进行另一个查询。然后使用该结果进行第三次查询。
但是如何从第二个查询中获取 userid 字段,以便从用户表中获取一个名称并将其连接到第三个查询的结果中?
请注意,一旦我弄清楚代码,我会将其转换为准备好的语句。在找出查询时,使用遗留代码对我来说更容易。
$selectaudioid = "SELECT audioid FROM subscribe WHERE userid = $userid";
$audioResult=$dblink->query($selectaudioid);
if ($audioResult->num_rows>0) {
while ($row = $audioResult->fetch_assoc()) {
$newaudio = $row[audioid];
$getallaudio = "SELECT opid, userid from audioposts WHERE audioid = $newaudio" ;
$getallresult = $dblink->query($getallaudio);
if ($getallresult->num_rows>0) {
while ($row = $getallresult->fetch_assoc()) {
$opid = $row[opid];
$opuserid = $row[userid];
$getreplies =
"SELECT * from audioposts ap WHERE opid = $opid AND opid
NOT IN (SELECT opid FROM audioposts WHERE audioposts.opid = '0' )";
$getreplyresults = $dblink->query($getreplies);
if ($getreplyresults->num_rows>0) {
while ($row = $getreplyresults->fetch_assoc()) {
$dbdata[]=$row;
}
}
}
}
}
} "SELECT * from audioposts ap WHERE opid = $opid AND opid
NOT IN (SELECT opid FROM audioposts WHERE audioposts.opid = '0' )";
$getreplyresults = $dblink->query($getreplies);
if ($getreplyresults->num_rows>0) {
while ($row = $getreplyresults->fetch_assoc()) {
$dbdata[]=$row;
}
}
}
}
}
}
echo json_encode($dbdata);
我需要的结果是$getreplyresults
由原始结果中的 $row[userid] 连接到每一行的 json 编码实例的行。
解决方案
这就是我最后所做的。现在我只需要弄清楚如何将其转换为准备好的语句以避免恶意注入。
$selectaudioid = "SELECT audioid FROM subscribe WHERE userid = $userid";
$audioResult=$dblink->query($selectaudioid);
if ($audioResult->num_rows>0) {
while ($row = $audioResult->fetch_assoc()) {
$newaudio = $row[audioid];
$getallaudio = "
SELECT ap.audioid, ap.title, us.name FROM audioposts ap
INNER JOIN audioposts a2 ON a2.audioid = ap.opid
INNER JOIN users us ON us.id = a2.userid
WHERE ap.opid = $newaudio AND ap.opid <> '0'
";
$getallresult = $dblink->query($getallaudio);
if ($getallresult->num_rows>0) {
while ($row = $getallresult->fetch_assoc()) {
$dbdata[]=$row;
}}}}
推荐阅读
- dynamics-crm - CRM Dynamics 快速创建表单标签
- php - 数组错误可能是 PHP 版本问题吗?
- javascript - 如何获取同一行的值
- java - 如何在字符串缓冲区输入循环之外获取 http 请求的输入流结果
- python - 转换嵌套列表以在 Mathematica 中使用
- css - 如何使边框左上方边框底部?
- flowtype - 如何从值数组中创建联合类型?
- javascript - 我如何获取给定语言的整个命名空间,或者如果它不存在则如何获取回退命名空间?
- julia - 如何将“Ptr”获取到“NTuple”的元素?
- javascript - 使用 csv 文件的 D3 条形图