[英]PHP execute multiple queries and while loop
I am having some difficulty executing multiple queries. 我在执行多个查询时遇到一些困难。
I have been reading about mysqli_multi_query
however I'm not sure how to implement this into my existing code. 我一直在阅读有关mysqli_multi_query
但是我不确定如何在现有代码中实现它。
Ideally I need to query two separate tables and display the results within the same while loop. 理想情况下,我需要查询两个单独的表并在同一while循环中显示结果。 Should this be a do-while, or am I way off? 这是应该做的事,还是我要离开?
My current code is; 我当前的代码是;
$id = $_GET['id'];
//setup first query
$query = ("SELECT pub_id, title FROM vw_ft_search WHERE pub_id = $id");
//setup second query
$query = ("SELECT phys_desc FROM vw_physical_descriptions WHERE publication_id = $id");
$result = $conn->query($query);
if($result === false) {
trigger_error('Wrong SQL: ' . $query . ' Error: ' . $conn->error, E_USER_ERROR);
}
while($row = $result->fetch_assoc()){
//result from first query
if (!empty($row['pub_id'])){ echo $row['pub_id'] . '<br />'; }
else echo "no information" .'<br />';
//result from first query
if (!empty($row['title'])){ echo $row['title'] . '<br />'; }
else echo "no information" .'<br />';
//result from second query here
}
New to this so any help/advice is appreciated. 这是新手,因此感谢您的帮助/建议。
Assuming these are 1:1 records you should try to JOIN
your queries instead. 假设这些是1:1记录,则应尝试JOIN
查询。 Also, I fixed your SQL injection 另外,我修复了您的SQL注入
$id = $conn->real_escape_string($_GET['id']);
$query = "SELECT vfs.pub_id, vfs.title, vpd.phys_desc
FROM vw_ft_search vfs
INNER JOIN vw_physical_descriptions vpd ON vfs.pub_id = vpd.publication_id
WHERE vfs.pub_id = $id";
The best way is to use a join statement: 最好的方法是使用join语句:
SELECT pub_id, title, phys_desc FROM vw_ft_search
JOIN vw_physical_descriptions ON vw_physical_descriptions.publication_id=vw_ft_search.pub_id
WHERE vw_ft_search.pub_id = $id"
The JOIN mushes the table together, the ON tells the server how to match the data up. JOIN将表混合在一起,ON告诉服务器如何匹配数据。
Can $result = $conn->query($query);
可以$result = $conn->query($query);
handle multi query? 处理多个查询? Maybe you should be using 也许你应该使用
$result = $conn->multi_query($query);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.