PHP foreach循环只给出1个结果

时间:2014-02-05 11:17:52

标签: php mysql arrays foreach

我有这个数组:

$cust = xtc_db_query("SELECT customers_id FROM orders");
$customers = xtc_db_fetch_array($cust);

当我尝试显示每一条记录时,我只得到第一条记录:

foreach ($customers as $v) {
    echo "ID: $v.\n <br>";
}

我尝试手动设置数组然后工作正常:

$customers = array(1, 2, 3, 17);

3 个答案:

答案 0 :(得分:7)

您的$customers数组将只包含一个值(查询的最后一个结果)。您需要使用while循环:

$cust = xtc_db_query("SELECT customers_id FROM orders");
while($customers = xtc_db_fetch_array($cust))
{
    // Use $customers here.
}

答案 1 :(得分:2)

$cust = xtc_db_query("SELECT customers_id FROM orders");
while($customers = xtc_db_fetch_array($cust)){
   echo "ID: $customers[customers_id].\n <br>";
}

答案 2 :(得分:0)

xtc_db_fetch_array将在每次迭代中返回一条记录。

要获取所有记录,您必须将xtc_db_fetch_array($cust)放入while循环中,如下所示。

$cust = xtc_db_query("SELECT customers_id FROM orders");
while($customers = xtc_db_fetch_array($cust)){
    print_r($customers);
}