While loop showing only one result - php

I want to show string outside while loop, but it only shows one result.
while($row = $result->fetch_assoc()) {
$myarr = array();
}
echo $myarr;
This shows only one result but I need all the results outside the while loop.
Could you please help me how is this possible?

I am not sure if you want the whole row returned from the query or just a single field.
If its the whole row then try
$myarr = array(); // initialize
while($row = $result->fetch_assoc()) {
$myarr[] = $row;
}
print_r($myarr);
This will give you an array containing n row arrays.

Problem :
You are just assigning the result one after again
$myarr = array();
Here, It means you're assigning the array() again and again, which replaces the old value
Solution / What You should do
1. You can assign it to an Array (Good Approach)
while($row = $result->fetch_assoc()) {
$myarr[] = $row['yourdbitem']; // or $row if you want whole row
}
print_r($myarr);
2. You can concat in each iteration (Bad Approach)
$somevariable = '';
while($row = $result->fetch_assoc()) {
$somevariable .= $row['yourdbitem']; // or $row if you want whole row
}
echo $somevariable
Note :
I have given good and bad approach to updating what you should do and what you should not do :)

Related

Unsure what PHP array is doing upon assigning

I have a DB snippit of code here... I'll post the relevant lines without error checking to make it smaller...
if ($stmt->bind_result($row[0], $row[1]) === false) etc...
then below I have...
<pre><code>
//fill the array up with an array of rows, then increment $ddp.
//$data[$ddp] is the row,
//$data[$dpp][0] is the rows first argument,
//$data[$dpp][1] is the rows 2nd argument returned etc...
$ddp = 0; // this increments up every fetch
while ($stmt->fetch()) {
$data[$ddp][0] = $row[0];
$data[$ddp][1] = $row[1];
$ddp++;
}
</code></pre>
The way I have it above WORKS.... but here is how I did it before and something weird was happening...
<pre><code>
$ddp = 0; // this increments up every fetch
while ($stmt->fetch()) {
$data[$ddp++] = $row;
// I ECHOd out $row here... and it did fetch 2 different rows...
}
</code></pre>
What happens is... when I did this...
$data[$ddp++] = $row;
$data[0][0] was the same as $data[1][0].
Why then if $row had different values on the 2 fetches... how did $data end up with 2 arrays the same?
I even tried
$data[] = $row;
and the same results. My fix was...
while ($stmt->fetch()) {
$data[$ddp][0] = $row[0];
$data[$ddp][1] = $row[1];
$ddp++;
}
WHY?
Sorry if this isn't the right place to put this but I did find a solution ahead of time and to save time I posted the answer and my question together.
Your two assignments are doing two subtly different things.
while ($stmt->fetch()) {
$data[$ddp][0] = $row[0];
$data[$ddp][1] = $row[1];
$ddp++;
}
This creates two entries in the array - the first will have the index [0][0], and be assigned the value in $row[0], and so on.
On the other hand, this:
while ($stmt->fetch()) {
$data[$ddp++] = $row;
// I ECHOd out $row here... and it did fetch 2 different rows...
}
is adding a single row to the database, and adding the whole of $row to $data[0] on the first run through. So whatever is returned from the database is added as it is - if you're getting an array back from fetch(), then you're adding an array inside your array.

PHP - Multidimensional Array

I am basically trying to fetch results from a SQL database and load that into a multidimensional array so i can use them later on in the page.
while($row = mysqli_fetch_array($result))
{
$send = array
(
array($row['Name'],$row['Email'],$row['Mobile'])
);
$count = $count + 1;
}
That is what i am using to get the results which if i print within the while loop it will echo all the results. However when putting it into the array it loads each result into the array as the first result. My initial plan was to use a counting variable to set where in the array the result was set to with this adding by one each time. I am not certain how to specify where to add the result i thought something along the lines of
$send = array[$count]
(
array.....
so i could then refer to the results as 0 to count length but i am not sure how to make this work. Or ,which i presume, if there is a much easier and better way of going about it. I am also not sure if this is necessary as surely the results seem to be in an array when gathered from the SQL database but i am unsure if this array is populated with each while loop or stored and can be accessed at any point
If any one can give me an example of something similar or point me at some documentation much appreciated
Try this:
$count = 0;
while ($row = mysqli_fetch_array($result)) {
$send[$count] = array($row['Name'], $row['Email'], $row['Mobile']);
$count++;
}
I have a better way for you. You could also use the id for your index, if you have one:
while ($row = mysqli_fetch_array($result)) {
$send[$row['id']] = array(
"Name" => $row['Name'],
"Email" => $row['Email'],
"Mobile" => $row['Mobile']
);
}
You can use:
$count = 0;
while($row = mysqli_fetch_array($result))
{
$send[$count] = $row;
$count ++;
}
Also you might want to use the table id as an array index, so you can access the records by ID later. In that case you can do:
while($row = mysqli_fetch_array($result))
{
$send[$row['id']] = $row;
}
You're declaring your array inside your loop. So it will reset it every time.
$send = array();
while($row = mysqli_fetch_array($result))
{
$send[] = array($row['Name'],$row['Email'],$row['Mobile']);
}

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.

Append non numeric key-values to an array

Trying to return a DB resultset as an array in my DAO:
I want to append string key-values to the array $retval in the below code. However, the array keeps getting overwritten each iteration instead of being appended to.
So at the end of the loop, I end up with 1 key-value instead of n pairs (n rows retrieved from the database). What am I doing wrong?
$retval = array();
while ($row = mysql_fetch_assoc($result)) {
foreach($columns as $var) {
$retval[$var]=$row[$var];
}
}
var_dump($retval);
$retval ends up as ["name"=>"Japan","capital"=>"Tokyo"] instead of the expected ["name"=>"Korea","capital"=>"Seoul"...."Japan"=>"Tokyo"] where columns are name and capital.
I'd have to see what your columns are, but shouldn't it be:
$retval = array();
while ($row = mysql_fetch_assoc($result)) {
$retval[ $row['country'] ] = $row['capital'];
}
It is because you are overwriting the same value (column name here.) Something like:
$retval['a'] = 1;
$retval['a'] = 2;
// ...
Instead use:
$retval[] = $row[$var];
HTH.

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.

Categories