为什么我一直将'array'作为查询的输出?

时间:2012-08-15 14:09:49

标签: php mysql html sql

我正在尝试进行查询以输出特定事件的参赛者数量。该表名为“payment”,事件的ID位于“itemid”列中。这是我创建的,但它似乎无法在浏览器中工作,但在phpMyAdmin中工作正常。每次我加载页面而不是看到一个数字时,我都会看到'Array'作为查询的输出。

修正了它:

$res = mysql_query("SELECT COUNT(*) AS entrants FROM payments WHERE itemid='Sample Event 1'") or die();
$row = mysql_fetch_array($res,MYSQL_ASSOC);

<?php echo $row['entrants']; ?>

5 个答案:

答案 0 :(得分:10)

你继续得到一个数组,因为你用它来获取它:

mysql_fetch_array($entrant_query);

fetch_array函数会将行AS返回一个数组。

还有很多其他方法可以从数据库中返回一行 - 虽然我猜你正在寻找的是fetch_row

您可以尝试使用var_dump来查看您要返回的内容。

<?php
$a = array(1, 2, array("a", "b", "c"));
var_dump($a);
?>

// output:

array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  array(3) {
    [0]=>
    string(1) "a"
    [1]=>
    string(1) "b"
    [2]=>
    string(1) "c"
  }
}

最后,mysql_*函数已弃用,您可能希望转而转到PDO。它更安全,更灵活,如果您刚刚开始,可以选择很多更好的选项。

答案 1 :(得分:2)

请查看

的文档
mysql_fetch_array($query);

http://pa.php.net/manual-lookup.php?pattern=mysql_fetch_array%28%29&scope=quickref

也尝试执行此代码

$f1 = mysql_fetch_array($entrant_query);
//this will  give u the print out of the associative array:
printr($f1);
//you can now access  each variable of the associative array by
//where the associative that prinr output
foreach($f1 as $value){
 echo $value;
}

答案 2 :(得分:1)

方法mysql_fetch_array()将查询结果加载到一个数组中,然后您可以使用该数组来访问您的数据。您可以遍历数组以提取所有数据,也可以直接访问特定数据。

答案 3 :(得分:1)

即使您的查询要返回记录数,并返回1个字段,您也正在调用函数mysql_fetch_array,因此只返回该行,但是行中有多个字段的数组。

通常如果你做了SELECT * from users,那么你将会一直四处寻找,直到没有更多的行,但是,因为你的查询返回1个字段,它只是一个1的数组,因为这是它的工作方式。 / p>

答案 4 :(得分:1)

include ("includes/db.php");
// Get data from the database for content
$res = mysql_query("SELECT COUNT(*) AS entrants FROM payments WHERE itemid='Sample Event 1'") or die();
$row = mysql_fetch_array($res,MYSQL_ASSOC);

<?php echo $row['entrants']; ?>

现在工作正常。

相关问题