多个结果+数组显示

时间:2011-11-14 20:54:20

标签: php

此查询与数据库中的两个字段匹配。我怎样才能从DB获取这两个名字?

        $product_q = mysql_query("SELECT * FROM `templates` WHERE `cat_id` = '$catid'") or die("<br/><br/>".mysql_error());
        $product_array = mysql_fetch_array($product_q);
        $product_name = $product_array['name']; //got the first results 'name'
        $product_name2 = $product_name[1]; // attempted to get the 2nd 'name'.

3 个答案:

答案 0 :(得分:0)

您必须遍历结果。像这样:

while($row = mysql_fetch_array($product_q) )
{
    $product_name = $row['name'];
    echo $product_name;
}

答案 1 :(得分:0)

你可以循环,或者这样做

 $product_q = mysql_query("SELECT * FROM `templates` WHERE `cat_id` = '$catid'") or die("<br/><br/>".mysql_error());
    $product_array = mysql_fetch_array($product_q); // First prod
    $product_name = $product_array['name'];

    $product_array = mysql_fetch_array($product_q); // Second prod
    $product_name2 = $product_array['name'];

循环:

while($r= mysql_fetch_array($product_q) )
{
    $productname= $r['name'];
}

对于结果中的每一行,您需要执行1次mysql_fetch_array。当没有剩下的行时,它将返回null。

如果你想要1个数组中的所有行,你可以这样做

$products = array();
while($r= mysql_fetch_array($product_q) )
{
    $products[] = $r;
}

// Echo first product
echo $products[0]['name'];

// Echo second product
echo $products[1]['name'];

... and so on

答案 2 :(得分:0)

如果您只想从两个表中获取名称,为什么不将它们放在要选择的列中?

$query = "SELECT table1.name as name1, table2.name as name FROM table1, table2";

这样你就可以按照自己想要的方式获得:

$product_array = mysql_fetch_array($query);
echo $product_array['name1'];
echo $product_array['name2'];