我正在尝试进行查询以输出特定事件的参赛者数量。该表名为"付款",事件的 ID 位于"itemid"列中。这是我创建的,但它似乎在浏览器中不起作用,但在 phpMyAdmin 中运行良好。每次我加载页面而不是看到数字时,我都会看到"数组"作为查询的输出。
修复了它:
$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']; ?>
你不断得到一个数组,因为你用这个来获取它:
mysql_fetch_array($entrant_query);
fetch_array函数会将行作为数组返回。
还有许多其他方法可以从数据库中返回一行 - 尽管我猜您要查找的方法是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。它更安全,更灵活,如果您刚刚开始,这是一个更好的学习选择。
请查看文档
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;
}
该方法mysql_fetch_array()
将查询结果加载到数组中,然后可以使用该数组访问数据。您可以遍历数组以提取所有数据,也可以直接访问特定数据。
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']; ?>
现在工作正常。
即使您的
查询要返回记录计数并返回 1 个字段,您也在调用函数mysql_fetch_array
,因此它只返回该数组,即行中有多少字段的数组。
通常,如果您这样做SELECT * from users
那么您会兜兜转转,直到没有更多的行,但是,仅仅因为您的查询返回 1 个字段,它只是一个 1 的数组,因为这就是它的工作方式。