如何在每个循环内的主查询中运行辅助查询

时间:2013-08-31 12:59:44

标签: php mysqli foreach

如何修改我的代码以允许我在每个循环中运行第二个查询?

现在我已经注释掉了第二个查询,因为我确定在删除斜杠之前需要进行一些更改。

    <?php

$mysqli = new mysqli('LOGIN DETAILS HERE');

if ($mysqli->connect_error) {
    die('Connect Error: ' . $mysqli->connect_error);
}

$query = "SELECT * FROM toptips WHERE userid = 2"; 
$result = $mysqli->query($query);

while($row = $result->fetch_array()) 
{ $rows[] = $row; }

foreach($rows as $row) { 

    $id = $row['id'];
    echo $row['time'] . " " . $row['course'] . " - " . $row['horse'] . " " . $row['description'] ."<br/>"; 

        // second query here
    // $query2 = "SELECT likes FROM Likes_table WHERE id = $id";
    // $result = $mysqli->query($query2);
    // while($row = $result->fetch_assoc()){
    // echo $row['likes'] . '<br />';
    // }

}

?>

1 个答案:

答案 0 :(得分:1)

更好地使用INNER JOIN:

SELECT 
    toptips.*,
    Likes_table.likes
FROM 
    toptips 
INNER JOIN
    Likes_table
ON
    Likes_table.id=toptips.id
WHERE
    toptips.userid = 2

通过删除内循环,这将为您节省大量资源。