different result by 'while' and 'foreach' - php

When looping through array using the 'while' I get good results, but when I do the same with foreach I don't get the same. The SELECT statement returns two rows:
731
732
$data = $mysqli->query("SELECT ...");
while($item = $data->fetch_array())
{
echo $item[0]."<br />";
}
This returns:
731
732
foreach ($data->fetch_array() as $item)
{
echo $item."<br />";
}
This returns:
731
731
What am I doing wrong in second aproach with 'foreach'?
Thank you very much!

That's because the array represents a single row in the returned result set. In your foreach loop, $data->fetch_array() will only ever be executed once and that will hold only a single row (which is 731). You'll have to cal fetch_array() again to get the next record. You'll have to use a while loop to get the records and push them into an array first, and then use foreach:
$resultset = array();
while($item = $data->fetch_array()) {
$resultset[] = $item;
}
foreach ($resultset as $row) {
echo $row;
}

Every time whe you call the fetch_array method, it returns one row from the DB as an array with the values of the fields.
So it does NOT return all the rows, but all the fields in one row.
And when you call it again, it will return array with the fields in the second row.
When all the rows in the query are returned, fetch_array() returns FALSE. In the while loop the $row variable becomes false and the lopp stops.

Related

foreach result only first letters of each row

Im getting the array from a function then using it on a foreach, it prints all rows, how can i print specific row when im using [0] after array it displays only first letters of both rows.
PHP FUNCTION:
public function selectedOffer($model_id){
$qq = mysqli_query($this->connection,"SELECT offerId FROM offers WHERE model_id='$model_id' ORDER BY id ASC");
$results = array();
while ($result = mysqli_fetch_array($qq)) {
$results[] = $result;
}
return $results;
}
FOREACH PHP
foreach ($mUser->selectedOffer($modelid) as $key) {
echo $key['offerId'][0];
}
also when i remove the [0] it prints both rows.
My question is how to print the first or second or which row i want?
To get specific/ first row,s column
$data = $mUser->selectedOffer($modelid);
echo $data[0]["offerId"];
And all rows column
foreach ($data as $key) {
echo $key['offerId'];
}
Use implode and array_column to echo a complete array column in one line of code:
echo implode("", array_column($yourarray, "offerId"));
The first argument of the implode is what should join the items in the array.
Your and the accepted answer has nothing that is why it's "", but it can be replaced with say: "<br>\n" if you want new line between each item of the array.

Understanding fetch_assoc()

I am trying to understand how/why fetch_assoc works the way it does.
I have the following piece of code:
$results = $connectToDb->fetch("SELECT * FROM customer");
$resultsArray = $results->fetch_assoc();
print_r($resultsArray); //print_r 1
while($row = $results->fetch_assoc()){
print_r($row); //print_r 2
}
The query returns 3 rows from a table.
Why does the 1st print_r return only the 1st row of the queried data but the 2nd print_r returns all 3? How does putting fetch_assoc into a while loop tell it to do the action more than once? I read that fetch_assoc returns either an associative array or NULL but I'm struggling to understand how the while loop "tells" fetch_assoc to fetch the next row, if that makes sense?
Thank you.
Lets try to understand your code and how it works:
$results = $connectToDb->fetch("SELECT * FROM customer");
A variable $results has a collection of rows which are returned by a query. The size of the collection can be from 0 to n.
$resultsArray = $results->fetch_assoc();
This line fetch the first element from the collection. If the collection is empty it will return NULL.
while($row = $results->fetch_assoc()){
}
It can be decoupled in the following steps:
Calculate $row = $results->fetch_assoc() and return array with elements or NULL.
Substitute $row = $results->fetch_assoc() in while with gotten value and get the following statements: while(array(with elements)) or while(NULL).
If it's while(array(with elements)) it resolves the while condition in True and allow to perform an iteration.
If it's while(NULL) it resolves the while condition in False and exits the loop.
I think it useful:
function get_posts(){
$posts = array();
if ($result = $mysqli->query("SELECT id, post_userid, name, lang, country, post_image, post_date, post_date_updated FROM posts ORDER BY `post_date` DESC ;")) {
while ($row = $result->fetch_assoc())
{
$posts[$row['id']] = $row ;
}
} else {
printf("Prepared Statement Error: %s\n", $mysqli->error);
}
return $posts;
}
in your case, if you want to print 3 rows each by each, you need to call this $result->fetch_assoc() as a three times.
for example, when you call the first time first row will be fetched and removed from array list. then 2 rows remain now.
in Second call second row will fetched and removed from array list.then 1 row remain now.
so you can call 3 times because you have a 3 rows. it will give null value if you call fourth times.because array list is empty now.
now come to the while($row = $results->fetch_assoc() this also do the same job which we discussed above.

Search PHP Array from results of SQL

I currently have an array in php that stores product names, normally 5 - 10. I would like to create something where the results of a SQL query is matched against the array to make sure they are all correct, and if not to show an error.
So far I have put the results into an array, then ran the query to get the results. I believe I need to put some sort of while loop with the results of the query and check the array in that while loop?
You have the array with the product name($products) and the results of the query($row).
While you loop trough the results you can check if the element is present,otherwise echo error and break the loop:
While(...) {
if(!in_array($row['retrivedprod'],$products)) {
echo 'error';
break;
}
}
You can cycle while receiving results from db with a while loop and checking results with the in_array function http://php.net/manual/en/function.in-array.php
$availability = 0;
$cart_products = array("book", "album");
$available_products = array();
while($row = mysql_fetch_array($result)) {
$available_products[] = $row['product'];
}
foreach($cart_products as $key => $value){
if (in_array($value, $available_products)){
$availability = 1;
}
}

How to Retrieve 1 Result from Custom MySQL fetch Function

Yesterday another user helped out with building a generic function for handling MySQL Queries. It looks like this:
function fetchAll($query) {
$res = mysql_query($query) or trigger_error("db: ".mysql_error()." in ".$query);
$a = array();
if ($res) {
while($row = mysql_fetch_assoc($res)) {
$a[]=$row;
}
}
return $a;
}
And to output the returned results I simply do the following:
$data = fetchAll("SELECT * FROM news_table ORDER BY id LIMIT 10");
foreach ($data as $row) {
echo $row['title'];
}
My question relates to outputting the result when there's only one result in the array. Like when displaying the current blog post of a page. I want to know if I can do it without first calling the foreach loop? Is there a way to output just the first result from the array as I do not need to loop through it.
Perhaps I could have an alternate function, as opposed to the fetchAll() one above? One that just outputs one row?
Cheers,
Scott
Yes. For example:
echo $data[0]['title'];
Basically your $data is a two-dimensional array, with the first dimension being the row number (count starts with 0), so you can access any of the rows directly if you know its number. If you only have one row, it's necessarily 0.
Just count the array
if(count($data) == 1) {
// Only one dataset
} else if(count($data) > 0) {
// foreach
} else {
// no content
}
echo $data[0]['title'];
Should print exactly what your looking for. In 2D arrays the first dimension is the array index and as array index start at 0, the above code will echo the first row in that array.

How to stop a while loop from running infinatly by making it stop when there are no more values in the array

I am trying to make pull key => value pairs out of an array by using a do { ....} while {there are values left inside the array.
I am using a function to query mysql for and then to insert all the values inside an array
function table_array($query) {
$table_array = array();
$data_fetched = false;
while ($array = mysql_fetch_assoc($query)) {
if (!$data_fetched) {
foreach ($array as $key => $value) {
$table_array[$key] = $value;
//$data_fetched = true;
}
}
}
return $table_array;
}
and then i am using another loop to extract the data from the array
function get_table($table_array) {
$header_written = false;
echo "<table border=1>";
if ($table_array) {
do {
echo "<tr>";
foreach ($table_array as $columns => $values) {
echo "<td> {$values} </td>";
}
echo "</tr>";
}while ($table_array);
}
echo "</table>";
}
However this causing my loop to run infinitely , why can't i use it just as though i would be doing while mysql_fetch_assoc is true.
I tried using a flag but that will stop it running after only one record is being extracted.
What you really need here are two foreach loops. The outer iterates over rows, and the inner iterates over columns:
echo "<table>";
// Iterates over rows
foreach ($table_array as $row) {
echo "<tr>";
// Iterates over columns (table cells)
foreach ($row as $col=>$value) {
echo "<td>{$value}</td>";
}
echo "</tr>";
}
echo "</table>";
Though your fetching process works, it can be simplified and improved. You don't need a foreach to assign columns to your $table_array. You can simply append the whole fetched row using the [] syntax. Not sure what the purpose of $data_fetched was, so I removed that as well
while ($array = mysql_fetch_assoc($query)) {
// Use the [] syntax to append the whole row onto $table_array
// No need to add each column of the fetched row separately
$table_array[] = $array;
}
Finally, the reason it didn't work the way you setup your do-while is that iterating over a regular array is not similar to fetching from a MySQL result set. The fetch calls will eventually return FALSE when no rows remain. Unless you are actively removing elements from an array while iterating over it, and eventually deleting the empty array, it will always evaluate to a boolean TRUE.
You need to use either foreach($array as $key => $value){ ... } or do{ ... } while ($array).
You should not use both, as you only have one set of data to loop over. I would stick with foreach as it is safer, and can do exactly what you need.
If you feel you need to use a do/while, then you need to pop a value off the $table_array each time you are inside the loop. This way, the $table_array will become empty at some point. Currently, in your code, the $table_array is always full so the while loop continues endlessly.

Categories