PHP: foreach msqli_query issue - php

I'm having an odd issue with a small piece of code right now. I've blown too much time trying to figure it out, so I figured I'd ask here. I have an array of integers ($childIDs) that I want to use to call individually on a stored procedure in a MySQL database. The connection is set up fine and this structure hasn't given me any problems until now.
The $childIDs array is set up properly, and the foreach loop does loop through each integer in the array as $currentChild. I first noticed that only the first item in the array would show up. After some testing, I found that $result was being set to a bool(false) after the first iteration of the loop. That being said, the query works fine with the numbers I'm using in the array.
So my question is why $result = mysqli_query($database, "CALL get_notes($currentChild);") is a false bool on everything but the first iteration of the foreach loop?
Here's the code:
$childIDs = array();
$childIDs = json_decode($_GET['childids']);
$noteList = array();
foreach ($childIDs as $currentChild)
{
if ($result = mysqli_query($database, "CALL get_notes($currentChild);"))
{
// Gathers all the notes for the child
while($row = mysqli_fetch_array($result))
{
// does stuff with each row, for now I'll just use an example...
var_dump($row);
}
}
}

This is solved by mysqli_next_result(). I needed to free up mysqli before every new iteration that called mysql_query(). Here's the working code:
$childIDs = array();
$childIDs = json_decode($_GET['childids']);
$noteList = array();
foreach ($childIDs as $currentChild)
{
if ($result = mysqli_query($database, "CALL get_notes($currentChild);"))
{
// Gathers all the notes for the child
while($row = mysqli_fetch_array($result))
{
// does stuff with each row, for now I'll just use an example...
var_dump($row);
}
}
mysqli_next_result($database);
}

Related

php mysql_fetch_array() not working as expected

$result = mysql_query($strSql);
foreach($bestmatch_array as $restaurant)
{
while($row = mysql_fetch_array($result))
{
if($restaurant == $row[0])
{
$value = $row[1];
}
}
}
What I am trying to do is sort the result of array formed by query according to the values stored in $bestmatch array.
I don't know what I am doing wrong but the 4th line just seems to run once. Please help guys. Thanx in advance.
php mysql_fetch_array() not working as expected
Your expectation is not right.
foreach($bestmatch_array as $restaurant)
{
// This loop will only run for first iteration of your foreach.
while($row = mysql_fetch_array($result))
{
}
// everything has been fetched by now.
}
That is a logically incorrect sequence.
You expect your inner loop to be called over and over again as many times as you have the outer loop run but record fetch does not work like that. For outer loop's first run all the rows in $result will be fetched and since you do not reset the counter after your while loop that means after the first run there will be no more rows for the next run.
Solution? Fetch the row from mysql first then use a simple in_array call to check whether that restaurant is there in your array.
$result = mysql_query($strSql);
while($row = mysql_fetch_array($result))
{
$name=$row[0];
if(in_array($name,$bestmatch_array))
$value=$name;
}
Store the results of the query in the array first:
$result = mysql_query($strSql);
$results_row = array();
while($row = mysql_fetch_array($result))
{
$results_row[] = array($row[0],$row[1]);
}
foreach($bestmatch_array as $restaurant)
{
foreach ($results_row as $key => $value)
{
if($restaurant == $results_row[$key][0])
{
$value = $results_row[$key][1];
}
}
}

PHP - Execute select query and loop through results

I am developing a web service using PHP. I am having some trouble while executing the select query. This is the code I'm using.
DB_Functions.php
public function getCompanies() {
$result = mysql_query("SELECT * FROM company");
// check for successful store
if ($result) {
return mysql_fetch_array($result,true);
} else {
return false;
}
}
GetCompanies.php
<?php
require_once 'include/DB_Functions.php';
$db = new DB_Functions();
$companies = array();
//$rows = $db->getCompanies();
while ($row = $db->getCompanies()) {
echo $row['companyName'];
$rowArr = array();
$rowArr['CompanyName'] = $row['companyName'];
$rowArr['CompanyID'] = $row['companyId'];
//array_push($companies, $rowArr);
$companies[] = $rowArr;
}
header('Content-Type: application/json');
$response=array("Companies"=>$companies);
$json = json_encode($response);
echo $json
?>
But the problem is in GetCompanies.php file the while loop is runs endless. The code appears to be ok. Any help would be appreciated.
When you do while ($row = $db->getCompanies()) { you are running the entire query over again and returning the 1st row each time. mysql_fetch_array returns one row.
What you need to do is have getCompanies() loop over all the rows and return an array.
public function getCompanies() {
$result = mysql_query("SELECT * FROM company");
// check for successful store
if ($result) {
$ret = array();
while($row = mysql_fetch_assoc($result)){
$ret[] = $row;
}
return $ret;
} else {
return false;
}
}
Now, getCompanies() will return you an array that you can just foreach over:
$rows = $db->getCompanies();
foreach($rows as $row){
// ...
}
Change your while loop declaration to something like
foreach($rows as $row) {}
And as Pavlin said, move the function call to getCompanies() outside the loop.
Also, how about modifying the query to select a particular set of fields from the database and directly sending them as the response without doing any additional processing?
Since you are implementing Select query without any condition(where clause). And since the company table has data it would always return true in the while loop this makes the while loop an infinite loop. For while to work properly the condition should become false to exit the loop.
Its not a programming flaw its a logical one.
The php docs have all the information you need. You're using the wrong function:
mysqli_fetch_array — Fetch a result row as an associative, a numeric
array, or both
vs
mysqli_fetch_all — Fetches all result rows as an associative array, a
numeric array, or both
Just change your return statement to
return mysqli_fetch_all($result);
or
return mysqli_fetch_all($result, MYSQLI_ASSOC);
to get an associative array.
And of course, you need to move your getCompanies call outside of the loop.
NOTE
php mysql_* functions have been depricated since version 5.5.* and are going to be removed from the language soon. You should look into mysqli_* or PDO.

While loop with assignment operator

I can't seem to figure out how this loop works in PHP:
$people = array();
while($row = $result->fetch_assoc())
$people[] = $row;
It seems as though the loop would just keep going, infinitely. But, it doesn't How exactly does this work? Can someone explain it to me step-by-step? I'm guessing that the while loop could also be written like this:
while(($row = $result->fetch_assoc()) == true)
The fetch_assoc fetches one result row at a time and stores it in $row. Since this is in a loop, you are fetching until you run out of rows
In the loop you are essentially pushing the $row value into a $people array
Your code:
$people = array();
while($row = $result->fetch_assoc())
$people[] = $row;
Example how its works (MySQL):
$people = array();
$result = mysql_query($query);
$rows_count = mysql_num_rows($result);
for ($i = $rows_count - 1; $i >= 0; $i--) {
mysql_data_seek($result, $i);
$people[] = mysql_fetch_assoc($result);
}
How U see first option is more compact.
fetch_assoc will return false either upon an error or when the cursor for the fetch hits the end of all the rows and no more rows can be fetched, so it will return false.
Every time you fetch for the query, a cursor keeps track of the last returned row and will continue to keep track ultimately till you finish reading all rows.
Edit: Sorry I was thinking about PDO and not mysqli, however it should be about the same thing.

Results of mysqli_query() returning null for last index

I am querying like this, in snippet below 1st loop takes column names and second loops push values in another array(i know this may not be an optimal way but this is what came in my mind and is solving my task). The problem is
$results = '';
$dataArray = array();
$columns_array = array();
$dataArray = array();
$results = mysqli_query($mysqli, ("SELECT
DISTINCT states_drg.`Provider State`,
SUM(states_drg.`Total Discharges`) AS discharges
FROM states_drg
GROUP BY states_drg.`Provider State`")
);
$columns_names = mysqli_fetch_assoc($results);
foreach ($columns_names as $key => $value) {
array_push($columns_array, $key);
}
array_push($dataArray, $columns_array);
foreach ($results as $result) {
array_push($dataArray, mysqli_fetch_row($results));
}
print_r($dataArray);
echo json_encode($dataArray, JSON_NUMERIC_CHECK);
exit;
);
Query runs absolutely fine in query browser, but when I take dump of print_r($dataArray); I get only 26 records where as I have around 51 records in total if I run the Query in Query Browser.
You're using mysqli totally wrong.
foreach($results as $result)
is NOT how you fetch data from a query result. You should have
while($row = mysqli_fetch_assoc($result)) {
$dataArray[] = $row;
}
And not to mention the multiple syntax errors in your pasted code...

Passing each row of a mysql query to a php array

i am running a mysql query to return all rows from a temp database, i then need to ammend some of the attributes in those rows so i am trying to return each row to an array so i can then reference the array and amend specific attributes of each row
im just stuck on how to get each row into its own array, im guessing i will need to use a 2d array for this however cannot figure out how to populate it from the mysql query into the 2d array. Im guessing it is something like i have tried below?
$result_array = array();
while ($row = mysql_fetch_assoc($res2)) {
$result_array[] = $var;
foreach($row as $key => $var) {
// Insert into array
echo $var;
}
however when trying this i am getting a notice saying:
Notice: Array to string conversion
any help pointing me in the right direction for this would be great
If I understand what you're asking for, you literally want each row from the SQL query to be a single index in the $result_array array?
If that's the case, you're already getting it with $row - you can add that directly to the array:
$result_array = array();
while ($row = mysql_fetch_assoc($res2)) {
$result_array[] = $row;
}
You can modify the values inside the array either when you're adding them to the global array, or after:
foreach ($result_array as $index => $row) {
$result_array[$index]['some_key'] = $row['some_key'] . ' [modified]';
}
Side-note (not answer specific)
I would recommend against using the old, deprecated mysql_ functions and instead favor MySQLi or PDO. Both of these are easy to use, more secure than the older methods and offer a large range of features such as prepared statements.
The above can be written with mysqli like:
if ($result = mysqli_query($connection, $query)) {
$results = array();
while ($row = mysqli_fetch_assoc($result)) {
$results = $row;
}
mysqli_free_result($result);
}

Categories