开发者

Querying a database with an array [duplicate]

This question already has answers here: PHP variable variables (6 answers) Closed 1 year ago.

I'm trying to query my database with an array, I'm trying to count the number of rows returned from the query for each country in my database, and also count the rows for each of these countries with a digit equalling 1. Using the following code:

<?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 WHE开发者_开发百科RE 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;   
        }      
}
 
?>

This is the error message I get:

Catchable fatal error: Object of class mysqli_result could not be converted to string in /home2/designwr/public_html/uwe/notalone/updates/percentage.php on line 9

Can anybody point me in the right direction?


You are using a string concatenation for your variable name: $r_.$country is the result of the two strings added together.

I would suggest using an array for the result set like:

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


Change:

$r_.$country

to:

${'r_'.$country}

And delete the loop (not it's contents):

while($row = mysqli_fetch_array($r_.$country, MYSQLI_ASSOC))

So in the end the code would look like this:

<?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;   
}

?>

References:

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

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


I take it line 9 is

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

I'm not sure what you're trying to do with $r_.$country = mysqli_query(...); but that's invalid syntax. Use an array:

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


check out the manual on mysqli/query. There you will find simple working examples to get the basics straight. counting is done by the count statement in the SQL-request.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜