我有点像一个PHP菜鸟。
我正在尝试使用数组查询我的数据库,我正在尝试计算数据库中每个国家/地区查询返回的行数,并计算每个国家/地区的行数等于1.使用以下代码:
<?php
include ('mysqli_connect.php'); // indclude mysql connection functions
$countries = array('united states','canada','united kingdom');
foreach($countries as $country){
//e.g. $r_spain holds the results from the query below with spain as $country
$r_.$country = mysqli_query($dbc,"SELECT * FROM feelings WHERE country = '$country' AND digit='1'");
//loop through the results
while($row = mysqli_fetch_array($r_.$country, MYSQLI_ASSOC)){
$rowCount = mysqli_num_rows($r_.$country);
echo $country."=".$rowCount;
}
}
?>
这是我收到的错误消息:
可捕获的致命错误:类的对象 mysqli_result无法转换 串入 /home2/designwr/public_html/uwe/notalone/updates/percentage.php 第9行
任何人都能指出我正确的方向吗?
谢谢,alsweeet
答案 0 :(得分:2)
您正在为变量名使用字符串连接:$r_.$country
是两个字符串一起添加的结果。
我建议使用数组作为结果集:
$r = array(); // after $countries
....
$r[$country] = mysqli_query......
答案 1 :(得分:1)
Change:
$r_.$country
to:
${'r_'.$country}
删除循环(不是它的内容):
while($row = mysqli_fetch_array($r_.$country, MYSQLI_ASSOC))
所以最后代码看起来像这样:
<?php
include ('mysqli_connect.php'); // indclude mysql connection functions
$countries = array('united states','canada','united kingdom');
foreach($countries as $country){
//e.g. $r_spain holds the results from the query below with spain as $country
${'r_'.$country} = mysqli_query($dbc,"SELECT * FROM feelings WHERE country = '$country' AND digit='1'");
$rowCount = mysqli_num_rows(${'r_'.$country});
echo $country."=".$rowCount;
}
?>
参考文献:
答案 2 :(得分:0)
我认为第9行是
$r_.$country = mysqli_query($dbc,"SELECT * FROM feelings WHERE country = '$country' AND digit='1'");
我不确定您要对$r_.$country = mysqli_query(...);
做什么,但这是无效的语法。使用数组:
$r[$country] = mysqli_query(...);
答案 3 :(得分:0)
查看mysqli/query上的手册。在那里,您将找到简单的工作示例,以便直接了解基础知识。计数由SQL请求中的count statement完成。