0

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

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

    <?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 />';
    // }

}

?>
4

1 回答 1

1

更好地使用 INNER JOIN:

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

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

于 2013-08-31T13:06:02.153 回答