Querying a database with an array [duplicate] - php

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

Related

why my php app code shows only one result from database? [duplicate]

This question already has answers here:
mysqli query results to show all rows
(4 answers)
Sql array only showing first result
(4 answers)
Closed 5 years ago.
I have write these kind of codes multiple times and it always worked great but now that I am on a different system it shows only 1 result.
the query is simple
$HOST = 'localhost';
$USERNAME = 'root';
$PASSWORD = '';
$DATABASE = 'db_test';
$con = mysqli_connect($HOST,$USERNAME,$PASSWORD,$DATABASE);
$sql = "SELECT * FROM test ";
$res = mysqli_query($con,$sql);
$res_array = mysqli_fetch_assoc($res);
echo json_encode($res_array);
mysqli_free_result($res);
mysqli_close($con);
I wonder if there is any settings that I have to change before running the app
Seriously, it's all over the docs:
mysqli_fetch_assoc Returns an associative array that corresponds to the fetched row or NULL if there are no more rows.
Note "the fetched row" part.
You need to do put your gathering in a cycle
$rows = [];
/* fetch associative array */
while ($row = mysqli_fetch_assoc($result)) {
$rows[] = $row
}
json_encode($rows);
This line $res_array = mysqli_fetch_assoc($res); will only fetch one record.
You need to loop over result-set object and get all data from that.So use while() loop like below
$res_array =[];
while($row = mysqli_fetch_assoc($res)){
$res_array[] = $row;
}
Reference:-
mysqli_fetch_assoc()
Replace this line
$res_array = mysqli_fetch_assoc($res);
with
while ($row = mysqli_fetch_assoc($res)) {
$res_array[] = $row;
}

PHP MySQL Database - All rows into Multi-Dimensional Array

It's been a long while since I touched PHP so, I just need a refresher of sorts.
I have an HTML form that captures several lines of data (dataA, dataB, dataC & dataD) and inserts them into a database table (dataAll). I will be entering rows upon rows of data into "dataAll". What I'm looking to do is create a display.php page, where the code will take all of the data and place each cell into an array, or the row of an array, for example:
new Array = [["dataA", "dataA", "dataA", "dataA", "dataA"],
["dataB", "dataB", "dataB", "dataB", "dataB"],
["dataC", "dataC", "dataC", "dataC", "dataC"],
["dataD", "dataD", "dataD", "dataD", "dataD"]];
But I cannot remember the syntax on how to perform this task. Any help would be greatly appreciated.
The database is named 'compdata', the table is 'dataAll', and each row is 'dataA', 'dataB', 'dataC', 'dataD'.
Please let me know if I need to supply more information.
Since you asked for All rows, so the simple code for query is written below:
<?php
//after connection to mysql db using mysql_connect()
$sql = "Select dataA, dataB, dataC, dataD from `compdata`.`dataAll`" ;
$result = mysql_query($sql) ;
if(mysql_num_rows($result) > 0 ){
while($row = mysql_fetch_array($result)){
$dataArray[] = $row ;
}
}
echo '<pre>';
print_r($dataArray) ;//you got the desired 2D array with all results
?>
Assuming you are used to the old mysql_xxx functions:
$data = array ();
$result = mysql_query ('select * from dataAll');
while ($row = mysql_fetch_array ($restult, MYSQL_ASSOC))
$data [] = $row;
Result:
$data = array (
0=>array ('col_1'=>'dataA', 'col_2'=>dataB...),
1=>array ('col_1'=>'dataA', 'col_2'=>dataB...)
);
If you only want the numbers and not the column names, use MYSQL_NUM.
However, mysql functions are being replaced with the more generic PDO object so you might want to look into that.
$stmt = $pdo->query ('select * from dataAll');
$result = $pdo->fetchAll (PDO::FETCH_ASSOC); // Or PDO::FECTCH_NUM
Same results as above.

mysql_fetch_array doesn't render the expect values of the SQL query

In the phpMyAdmin interface I run the following SQL query:
SELECT id FROM table WHERE family = '1' AND type = 'B1'
and receive the following results:
'1', '18546269', '51534064' which are correct.
Then I wrote the following code in PHP:
$query = "SELECT id FROM table WHERE family = '1' AND type = 'B1'";
$result = mysql_query($query);
$array = mysql_fetch_array($result);
echo '(', implode(',',$array) ,')';
But receive the following result:
(1,1) which I didn't expected.
I thought that (1,18546269,51534064) would be displayed.
Then I wrote the following code to verify what should be displayed:
print_r ($array);
and was very surprised that the values were:
Array ( [0] => 1 [id] => 1 ).
In the end I wrote:
while($array = mysql_fetch_array($result)) {
echo $array['id'],',';
}
and as expected received exactly this:
1,18546269,51534064,
which I can't use because I need a string exactly like that: (1,18546269,51534064).
In fact I 'just' need a variable that gives me the same values of the SQL query that I run in phpMyAdmin.
I'm really confused and would be great if one of you guys could help me.
Solutions with mysqli would be appreciated as well. :-)
$query = "SELECT id FROM table WHERE family = '1' AND type = 'B1'";
$result = mysqli_query($link, $query);
$ids = '';
while($row = mysqli_fetch_array($result)) $ids .= $row['id'].',';
// Filter the text a bit
$ids = rtrim($string, ',');
$ids = '('.$ids.')';
echo $ids;
You basically initiate a variable, put all the ids in it, remove the last comma, append the brackets and that's it.
As documented under mysql_fetch_array():
Return Values
Returns an array of strings that corresponds to the fetched row, or FALSE if there are no more rows. The type of returned array depends on how result_type is defined. By using MYSQL_BOTH (default), you'll get an array with both associative and number indices.
[ deletia ]
Example #2 mysql_fetch_array() with MYSQL_NUM
<?php
mysql_connect("localhost", "mysql_user", "mysql_password") or
die("Could not connect: " . mysql_error());
mysql_select_db("mydb");
$result = mysql_query("SELECT id, name FROM mytable");
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
printf("ID: %s Name: %s", $row[0], $row[1]);
}
mysql_free_result($result);
?>
That is to say, the function returns only one row, by default as an array consisting of both associative and numeric-indexed columns from the resultset. You want instead make multiple calls to the function, with a suitable result_type parameter (as shown above).
mysql_fetch_array fetches array of row, not array of column. That means, if you would have ID and name, the fetched array would contain on each row an id and a name.
Quite a simple modification of your code that should fix the problem would be
$i=0;
$data=array();
while($array = mysql_fetch_array($result)) {
$data[$i]=$array['id'];
$i++;
}
echo '(', implode(',',$data) ,')';

Splitting a php array from mysql query

I have been working on this for hours on end trying to split the resultant mysql query into their usable variables and I just don't know what I am doing incorrectly. I no longer get the resource ID# but now all I get is "array" from the variables when I print_r. I am trying to get the 3 fields from the select statement in their own array and use the values. I have been pulling my hair out trying to get this to create usable data. Any help is greatly appreciated as I feel I could spend many, many more hours tinkering and just seem to be on the wrong track.
$Query = "SELECT guardian.Email, child.CFName, guardian.FName
FROM child
INNER JOIN uaccount ON child.ANum = uaccount.ANum
INNER JOIN guardian ON guardian.ANum = uaccount.ANum
WHERE uaccount.ANum = '$ANum';";
$result = mysql_query($query);
$test = mysql_fetch_array($result, MYSQL_BOTH);
print_r('this is the test '.$test."<br/>");
while($row = mysql_fetch_assoc($test, MYSQL_BOTH))
{
print_r('this is the row '.$row."<br/>");
foreach($row as $rows)
{
$info = mysql_fetch_assoc($rows, MYSQL_BOTH);
$Email = $info['0'];
$FName = $info['1'];
$CFName = $info['2'];
}
}
Thank you very much for your assistance thus far. With a combination of everyone's help I have been able to pull the values from the first level of the array with the following code :
$query = "SELECT guardian.Email, guardian.FName, child.CFName
FROM guardian
INNER JOIN uaccount ON child.ANum = uaccount.ANum
INNER JOIN guardian ON guardian.ANum = uaccount.ANum
WHERE uaccount.ANum = '$ANum';";
$result = mysql_query($query);
$info = mysql_fetch_array($result);
$Email = $info['0'];
$FName = $info['1'];
$CFName = $info['2'];
However, that is only returning me 1/3rd of the data as each account has 3 guardian email addresses related to it. Where I should be getting about 2000 rows returned, I am only getting 670. That is why I was nesting another layer inside the orginal posting and why I was attempting to pull a fetch_assoc from itself. If you cannot pull an array from itself, how do you "de-nest" so to speak? Any and all help is greatly appreciated.
$emQuery = "SELECT guardian.Email, child.CFName, guardian.FName
FROM child
INNER JOIN uaccount ON child.ANum = uaccount.ANum
INNER JOIN guardian ON guardian.ANum = uaccount.ANum
WHERE uaccount.ANum = '$ANum'";
$result = mysql_query($query);
$Email = array();
$FName = array();
$CFName = array();
$test = mysql_fetch_array($result, MYSQL_BOTH);
print_r('this is the test '.$test."<br/>");
while($row = mysql_fetch_assoc($test, MYSQL_BOTH))
{
echo 'this is the row ';
print_r($row);
echo '<br/>';
//$info = mysql_fetch_assoc($rows, MYSQL_BOTH);
$Email[] = $info['Email'];
$FName[] = $info['FName'];
$CFName[] = $info['CFName'];
}
To the best of my understanding this is what you are trying to do.
Some highlights:
print_r can only get a reference to a valid php array, no strings included.
mysql_fetch_assoc fetches a line out of a result set referenced by a variable, and then moves the reference to point to the next row.
You cannot call this function on a the result of it self, as it is not valid syntax.
In general, you'll be better off using PDO or mysqli_ functions at least, as it is by far more secure, by allowing you to use parameter binding instead of just using use input as part as your SQL.
You should just loop through the rows of your result once like so:
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
// print_r($row); Debug here if you want.
$Email = $row['Email'];
$FName = $row['FName'];
$CFName = $row['CFName'];
}
Note: You were providing a second parameter to mysql_fetch_assoc() which only takes one parameter (the result from a query). See the doc here.
mysql_fetch_array() takes another parameter that specifies what type of array to return.
Generalized PDO example out of a project of mine ($sql would be your $Query string):
$qry = $pdo->query($sql);
$all=array();
$idx=0;
while($fields=$qry->fetch( 'PDO::FETCH_ASSOC' )){
$all[key($fields)][$idx]=$fields[key($fields)];
while(next($fields)!==false){
$all[key($fields)][$idx]=$fields[key($fields)];
}
$idx++;
}
The $all variable will hold an array which in turn holds an array for each of the columns you've selected.
Like that you can do neat things like array_combine($all['Email'],$all['Fname']) and you'd get an array where the key is the Email column and the value would consist of the Fname column.

Why do I sometimes get no rows when perfoming a SQL query in PHP

I have a SQL table that is full of data. I am using the following code to extract column values and put them into an array. This works fine as when I do var_dump(array), I get the elements in the array printed out, and they look correct. However, sometimes I just get empty elements. This basically means that the column values were not obtained. Does anyone know why I sometimes get no results when the table is full of records?
$names = array();
$dob = array();
mysql_connect("localhost", "xxx", "xxx")or die("Error");
mysql_select_db("details")or die("Error");
$query="SELECT * FROM members";
$result=mysql_query($query);
while ($row = mysql_fetch_assoc($result) ){
$names[] = $row["name"];
$dob[] = $row["dob"];
}
var_dump($names);
var_dump($dob);

Categories