-1

我正在尝试使用第一个数组的第二个数据库查询运行 2 个数据库查询,任何人都知道为什么这会阻止页面加载?

$query = $this->db->query("SELECT category_id FROM listings WHERE listing_id = '1' LIMIT 1");
foreach ($query->result() as $row)
{
    $query2 = $this->db->query("SELECT listing_title FROM listings WHERE listing_type =     '".$row->category_id."' ORDER BY RAND() LIMIT 2");
    foreach ($query2->result() as $row)
    {
        echo $row->listing_title;
    }
}
4

3 回答 3

2

您正在覆盖内部循环中的外部 $row

$query = $this->db->query("SELECT category_id FROM listings WHERE listing_id = '1' LIMIT 1");
foreach ($query->result() as $row)
{
    $query2 = $this->db->query("SELECT listing_title FROM listings WHERE listing_type =     '".$row->category_id."' ORDER BY RAND() LIMIT 2");
    foreach ($query2->result() as $row2) // <--- $row2 not $row
    {
        echo $row2->listing_title;
    }
} 
于 2013-03-12T01:22:21.493 回答
0

尝试这个:

(利用准备语句、prepare() 函数等)

$query = "SELECT category_id FROM listings WHERE listing_id = '1' LIMIT 1;";
$query2 = "SELECT listing_title FROM listings WHERE listing_type = :categoryId ORDER BY RAND() LIMIT 2;";

$db = $this->db;

$statement = $db->prepare($query);
$statement->execute();
$statement->setFetchMode(PDO::FETCH_ASSOC);
while($row = $statement->fetch())
{
    $categoryId = $row['category_id'];

    $statement2 = $db->prepare($query2);
    $statement2->execute(array(':categoryId' => $categoryId));
    $statement2->setFetchMode(PDO::FETCH_ASSOC);
    while($row2 = $statement2->fetch())
    {
        $listingTitle = $row2['listing_title'];
        echo $listingTitle;
    }
}
于 2013-03-12T01:42:09.673 回答
0

这不是很好的代码。当 Select 查询有 时为什么要使用foreach循环Limit 1

由于您要使用 list_id=1 的类别 ID(使用 LIMIT 1),因此您的代码可以缩短为:

SELECT listing_title FROM listings WHERE listing_id=1 ORDER BY RAND() LIMIT 2

此外,ORDER BY RAND()它是大桌子上的大资源杀手。我建议找到一种更合适的方式来订购您的结果。

编辑:我将使用的完整代码:

$db=$this->db; //Just so we don't have to keep referencing $this (assuming you are not in a class)

$sql="SELECT listing_title 
FROM listings 
WHERE listing_id=? 
ORDER BY RAND() 
LIMIT 2";

$statement=$db->prepare($sql);
$statement->execute(array(1));

while($result=$statement->fetchObject()){
    echo $result->listing_title;
}
于 2013-03-12T01:42:23.143 回答