首页 > 解决方案 > 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 }; }; ?>

标签: 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 注入?


推荐阅读