如何在PHP中打印Object的值,这是从SQL中获取的行?

时间:2012-10-22 09:26:53

标签: php sql

我试图打印我的PHP对象的值' $ mon'这是所有月份的平均值.....

和我的数据提取代码为

$result = mysql_query("SELECT b_year, sum(m1) as m1, sum(m2) as m2, sum(m3) as m3, sum(m4) as m4, sum(m5) as m5, sum(m6) as m6, sum(m7) as m7, sum(m8) as m8, sum(m9) as m9, sum(m10) as m10, sum(m11) as m11, sum(m12) as m12  
            from s_budgets as b INNER JOIN users as u on b.u_id = u.id WHERE b_year=YEAR( CURDATE( ) )
GROUP BY b_year " );
$mon=mysql_fetch_array($result)

我显示这些值的代码如下....

 <?php echo $mon->m4;?>,
 <?php echo $mon->m5;?>,
 <?php echo $mon->m6;?>,

如何打印物品&#39; $ mon&#39;有几个属性?

4 个答案:

答案 0 :(得分:2)

$mon=mysql_fetch_array($result) fetch a result row as an associative array, a numeric array, or both ..

echo $mon['m4'];

如果您想将结果作为对象,请使用以下方式

$mon = mysql_fetch_object($result)
$mon->m4
  

请开始使用Mysqli或PDO进行新开发。

答案 1 :(得分:2)

您需要使用mysql_fetch_object()而不是mysql_fetch_array()才能以对象格式访问数据。

答案 2 :(得分:1)

如果你需要它用于调试目的,一个简单的

var_dump($mon);

为您提供$mon的所有属性。

否则尝试迭代结果数组:

while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
     echo $row['m4']; // etc.
}

答案 3 :(得分:1)

$ mon不是对象,因为mysql_fetch_array从MySQL资源中获取数组。你必须这样访问你的数组:

<?php echo $mon['m4']; ?>,
<?php echo $mon['m5']; ?>,
<?php echo $mon['m6']; ?>,

如果您想要一个物品,则需要使用mysql_fetch_object