我有这样的查询:
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']
);
}
对于$expenses
以上的每个人都会返回以下输出:
3 | 5 | 1.5000 | 5 | Lunch
4 | 6 | 4.6600 | 6 | Dinner
第一顿“午餐”会怎样?如何让PHP输出与直接MySQL查询输出相同?
答案 0 :(得分:2)
您在mysql_fetch_accoc
之前致电while
。不。
您还应该意识到{@ 1}}将被弃用并升级您的代码以使用PDO或mysqli正确参数化查询
答案 1 :(得分: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 />';
}