0

我有一个这样的查询:

SELECT * FROM `purchases` p 
JOIN `purchase_types` pt ON p.purchase_type = pt.node

当我在 PHPmyAdmin 中运行它时,它会返回正确的结果集,如下所示:

node | purchase_type | amount_spent | node | name
--------------------------------------------------
2    | 5             | 8.5000       | 5    | Lunch
3    | 5             | 1.5000       | 5    | Lunch
4    | 6             | 4.6600       | 6    | Dinner

这是我的 PHP 代码:

$sql = "SELECT * FROM `purchases` p 
        JOIN `purchase_types` pt ON p.purchase_type = pt.node";

$query = mysql_query($sql);
$result = mysql_fetch_assoc($query);

$purchases = array();
while($row = mysql_fetch_assoc($query)) {
    $purchases[] = array(
        'name' => $row['name'],
        'amount_spent' => $row['amount_spent']
    );
}

for eaching over$expenses返回以下输出:

3    | 5             | 1.5000       | 5    | Lunch
4    | 6             | 4.6600       | 6    | Dinner

第一次“午餐”会发生什么?如何让 PHP 输出与直接 MySQL 查询输出相同?

4

2 回答 2

2

mysql_fetch_accoc你之前打电话while。不。


您还应该意识到这ext/mysql将被弃用并升级您的代码以使用带有 PDO 或 mysqli 的正确参数化查询

于 2013-05-01T03:19:52.703 回答
0

尝试使用 mysql_fetch_array,

$purchases = array();
while($row = mysql_fetch_array($query)) {
    $purchases[] = $row;
}

如果你想获取数据就做

foreach($purchases as $key => $value)
{
    $name = $value['name'];
    $amount_spent = $value['amount_spent'];

    echo 'name : '.$name.' , amount spent '.$amount_spent.'<br />';
}
于 2013-05-01T03:40:17.183 回答