从阵列运行2个数据库查询

时间:2013-03-12 01:19:33

标签: php mysql

我正在尝试使用第一个数组运行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;
    }
}

3 个答案:

答案 0 :(得分: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 $row2) // <--- $row2 not $row
    {
        echo $row2->listing_title;
    }
} 

答案 1 :(得分:0)

试试这个:

(利用prepare语句,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;
    }
}

答案 2 :(得分:0)

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

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

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;
}