【问题标题】:Querying a database with an array [duplicate]使用数组查询数据库[重复]
【发布时间】:2011-07-01 09:04:35
【问题描述】:

我正在尝试使用数组查询我的数据库,我正在尝试计算数据库中每个国家/地区的查询返回的行数,并计算每个国家/地区的数字等于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 行

谁能指出我正确的方向?

【问题讨论】:

  • 你为什么使用 mysqli 而不是 mysql? mysqli 并没有真正用得那么多...
  • 我不知道 :) 我是这么教的,是不是很糟糕?
  • 非常错误......mysqli 是连接到 MySQL 的 OO 方式,所以它现在是第一选择。
  • 我认为您应该使用 mysqli 或 PDO 并利用它们提供的准备好的语句。
  • 我想知道,这些 mysqli 宣传人员中是否至少有一个会使用准备好的语句提出适当的解决方案。恐怕他们都没有真正使用它;)

标签: php arrays mysqli


【解决方案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;   
}

?>

参考资料:

http://php.net/manual/en/language.variables.variable.php

http://www.php.net/manual/en/mysqli-result.num-rows.php

【讨论】:

    【解决方案2】:

    查看mysqli/query 上的手册。在那里,您将找到简单的工作示例来了解基础知识。计数由 SQL 请求中的count statement 完成。

    【讨论】:

      【解决方案3】:

      我认为第 9 行是

       $r_.$country = mysqli_query($dbc,"SELECT * FROM feelings WHERE country = '$country' AND digit='1'");
      

      我不确定您要对 $r_.$country = mysqli_query(...); 做什么,但这是无效的语法。使用数组:

      $r[$country] = mysqli_query(...);
      

      【讨论】:

        【解决方案4】:

        您正在为变量名使用字符串连接:$r_.$country 是两个字符串相加的结果。

        我建议对结果集使用数组,例如:

        $r = array();     // after $countries
        ....
            $r[$country] = mysqli_query......
        

        【讨论】:

          猜你喜欢
          • 2020-01-30
          • 2014-09-23
          • 1970-01-01
          • 1970-01-01
          • 2018-10-24
          • 2018-08-04
          • 1970-01-01
          • 2019-10-15
          • 2017-09-22
          相关资源
          最近更新 更多