我有一个包含不同地区渔业的数据库。我正在使用以下命令:
$sql ="SELECT region FROM table WHERE region='Fife'";
$res = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_assoc($res)){
$total = array ($sql);
echo count($total);
这给了我 (111111111111111) 作为输出。但是,我希望它返回(15)。目前只有15个条目与"Fife"匹配
任何人都可以建议我如何改进我的代码以获得预期的结果?
使用 MySQL 的count()
:
$sql ="SELECT count(*) AS total FROM table WHERE region='Fife'";
$res = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_assoc($res);
echo $row['total'];
$sql ="SELECT region FROM table WHERE region='Fife'";
$res = mysql_query($sql) or die(mysql_error());
$total = array();
while($row = mysql_fetch_assoc($res)){
$total[] = array ($sql);
}
echo count($total);
如果要保留记录
您实际上可以在SQL中进行计数,这要快得多。
$sql ="SELECT COUNT (*) FROM table WHERE region='Fife'";
$c = mysql_query($sql) or die(mysql_error());
print $c;