php - SQL循环内的PHP/SQL查询表
问题描述
我试图在现有循环中查询另一个表。这可能吗?
所以我从外部循环中获取一个变量并尝试使用该变量从另一个表中获取数据。
以下内容完全消除了我的查询......
<?php $sql = "SELECT t1.id as messageID, t1.from_id, t2.full_name, t2.title FROM table1 t1 JOIN table2 t2 on t2.id = t1.user_id WHERE t1.user_id = '$userid' AND t1.unread = 0";
$result = $conn->query($sql); if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) {; $from = $row["from_id"]; $messageID = $row["messageID"]; ?>
<tr>
<td><?php echo $row["full_name"];?></td>
<td><?php echo $row["title"];?></td>
</tr>
<?php }; }; ?>
解决方案
只要有可能,您应该避免在循环中使用 SQL,并尝试一次性获取所有数据。在这种情况下,您可以使用JOIN
在第一条语句中获取用户名。就个人而言,我还会仅列出您要获取的列,而不是使用*
...
$sql = "SELECT t1.id as messageID, t1.from_id, t2.full_name, t2.title
FROM table1 t1
JOIN table2 t2 on t2.id = t1.user_id
WHERE t1.user_id = '$userid' AND t1.unread = 0";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {;
$from = $row["from_id"];
$messageID = $row["messageID"];
?>
<tr>
<td><?php echo $row['full_name'];?></td>
<td><?php echo $row["title"];?></td>
</tr>
<?php
}
}
无法测试它,但应该更有用。
您还应该查看准备好的语句,因为这可以帮助解决各种问题 -如何防止 PHP 中的 SQL 注入?
推荐阅读
- r - 如何从r中的累积列创建列?
- laravel - 在 laravel 上编辑数据时无法更新图像
- python - 如何在python中检查从GUI输入的字符串的有效性
- html - 与 HTML 相关的“布局”的工作定义是什么?
- python-3.x - 在python 3中使用tkinter按下按钮后如何删除按钮?
- java - 方法不会覆盖或实现超类型 ExoPlayer 中的方法
- firebase - Firebase 安全规则 newData 不起作用
- cucumber - 标签过滤系统 - Cucumber
- node.js - 在“npm start”上使用 WSL + Electron + Typescript 获取 SUID Sandbox Helper 错误
- html - CSS 网格日历 - 事件时间跨度