how does the while loop iterate assoc array - php

how does
while($result=mysqli_fetch_assoc($query)){ echo $result['name'];}
iterate all the rows in the table, i mean it should keep printing the first row only how does it print all rows i think i am fetching only the array of first row

Take an example of this loop
$i=0;
while($i<5)
{
// do something
$i++;
}
That loop will only stop when your condition ($i<5) results in FALSE
When you do
while($result=mysqli_fetch_assoc($query))
This loop willl also keep working as long as your fetch returns a row, which is not FALSE. The only different thing happening here is that you are not doing the increment yourself, when mysqli_fetch_assoc fetches a row it automatically increments the internal pointer of that result set to the next row so when you call the same function again you get the next row and when there are no more rows left it will return NULL which means $result=NULL; which will result in FALSE and you will exit the loop.

Related

Create multidimensional array without double values

I have a array, from sql query with several colums.
One of this is text column with names of clients.
$data['obchody']= $this->audytp_m->audytpro_obch();
$data['obchody_wsp']=array();
From this I create new array, for next step of my program:
$I=0;
foreach ($data['obchody'] as $row)
{
if(array_search($row['nieruchomosc'], array_unique(array_column($data['obchody_wsp'], 'nieruchomosc'))) ==0)
{
$data['obchody_wsp'][$I]['nieruchomosc']=$row['nieruchomosc'];
$data['obchody_wsp'][$I]['AudytPROInformacjaOUsludze']=$row['AudytPROInformacjaOUsludze'];
$data['obchody_wsp'][$I]['AudytPROCzestotliwoscObchodow']=$row['AudytPROCzestotliwoscObchodow'];
}
$I++;
}
$I=0;
I use array_search to find value in new table ( column: nieruchomosc). And generally its work, but sametimes one or more of the value is multiplify :(
I don't know why:
OK, I find the error in code.
array_search returns index of row, and "==0" is logical error, 0 is first row in array.
After var_dump i found, when array_search not find value, return's "false".
This below code working now fine:
if( array_search($row['nieruchomosc'], array_column($data['obchody_wsp'], 'nieruchomosc'))===false)

array isn't combining with loop in php

i've a array problem couldn't just solve it:
here's the code that is already in a foreach loop. i'm getting the $row->class_id value from this loop. it works fine and get me the total students row within an array and i preserved it in $total_student_of_this_class variable. i used another foreach loop for storing the result of first loop and then second loop and so on. but this loop gives only first loop result.
i need to combine the all array of total iteration of the loop.
$total_student_of_this_class =
$this->db->select('student_id')->where('class_id',
$row->class_id)->get('student')->result_array();
echo count($total_student_of_this_class);
// prints 2 in the first row of the output table and 5 in the second
row for me.
$total_student = array();
foreach ($total_student_of_this_class as $tt)
{
$total_student[] = $tt;
}
echo '<pre>';
print_r($total_student_of_this_class);
echo '</pre>'
echo count($total_student);
// prints only 2 outside the loop (not 7)
pls someone help me.
The problem here is seems to be with $total_student = array();: initializing array inside an other loop it always starts it from zero values array, so you get only results from one iteration inside it and doesn't collect all datas.
You can also look at array_merge php function.

Get out of loop

I have such rows in my table in MySQL ( I wont post all the data which is in "table1", because I use only this) :
From this table I get each value with foreach loop and group it by "time_from" ascending order, because I need to start from the lowest one.
With echo I print such table in html :
I add the values to the table by checking the "time_from" database with those values that are printed with for loop. The problem is that when I don't know how to stop the loop at the exact time so it should start not from the beginning but rowwhere it stopped.
foreach ($mydbdata as $row) { //only as example,because I get all the data normally,checked everything with echo to get sure.
for($time = 0; $time <= 24; $time++)
{
if($row['time_from'] == $time) {
echo '<td>OK</td>';
}
else {'<td>BAD</td>';}
}
}
The problem is that it prints all the row, adds data corresponding to if clause, but when it goes to second check it prints again all the cells in the same row. I need somehow to stop the loop and get back,but start not from the start, but from that value on which it stopped. Any ideas how to do that? I have tried with "break;" but anyway, it is not starting from the place I need.

Result is empty after while loop

Why is this not possible? Is there some way I can make the resolut not to be empty?
$sqlAllInfo = "SELECT item1, item2 FROM example";
$resAllInfo = mysql_query($sqlAllInfo);
while($rowAllInfo = mysql_fetch_assoc($resAllInfo)){
echo $rowAllInfo['item1'];
}
$rowAllInfo = mysql_fetch_assoc($resAllInfo);
echo $rowAllinfo['item2'];
Thanks for your time
No, the result will always be empty after your while loop, because the while loop extracts all value from the result resource..the while loop continues looping while there is still information to extract, and will finish when it is empty or when an error occurs
if you ment to get the last entry
$rowAllInfo still contains the last entry ;)
You are looping through the result set using while until there are no more results left. The while loop exits when mysql_fetch_assoc returns false, because there are no more results. Calling mysql_fetch_assoc again still means that there are no more results.
This line:
while($rowAllInfo = mysql_fetch_assoc($resAllInfo)){
assigns a new value to rowAllInfo and afterwards checks whether it is still "true"-ish (as "true" as PHP can be ;-) )
Now, after the last row is fetched, mysql_fetch_assoc() will return false, which is then assigned to $rowAllInfo. As $rowAllInfo is now "false", the loop will not execute anymore, but - look - it's too late! You Variable already has the value false assigned to it.
Even after that, you call mysql_fetch_assoc() once again. But, as you have already fetched all rows within your loop, no more rows are left, and once again $rowAllInfo is set to "false".
So, whatever you are trying to do - this is probably not your way. A common way to achieve what I understand you are trying to do is the following:
$allRows = array();
while( $row = mysql_fetch_assoc($res) ) {
$allRows[] = $row;
}
// show the array we just created...
echo print_r( $arrRows, 1 );

Why you should not use mysql_fetch_assoc more than 1 time?

Some people say you should not use mysql_fetch_assoc more than one time, why is that?
e.g.: I want to display two tables one with users who paid for membership, other with users who did not, so instead of querying database 2 times I query it one time and get $result variable with both types of users then I run loop mysql_fetch_assoc and see if list['membership'] = 'paid' then echo ...
Second time I loop loop mysql_fetch_assoc and see if list['membership'] = 'free' then echo ...
What uses less resources considering I got about equal amount of users who registered and unregistered.
Think of your query result set as a sausage, and mysql_fetch_assoc() as a knife that slices off a piece of that sausage. Every time you fetch a row, another piece of sausage is cut off, and it's always a NEW piece of sausage. You can't go and cut off a previously cut piece, because it's been eaten already.
Quote by Typer85 (link):
Please be advised that the resource result that you pass to this function can be thought of as being passed by reference because a resource is simply a pointer to a memory location.
Because of this, you can not loop through a resource result twice in the same script before resetting the pointer back to the start position.
For example:
<?php
// Assume We Already Queried Our Database.
// Loop Through Result Set.
while( $queryContent = mysql_fetch_row( $queryResult ) {
// Display.
echo $queryContent[ 0 ];
}
// We looped through the resource result already so the
// the pointer is no longer pointing at any rows.
// If we decide to loop through the same resource result
// again, the function will always return false because it
// will assume there are no more rows.
// So the following code, if executed after the previous code
// segment will not work.
while( $queryContent = mysql_fetch_row( $queryResult ) {
// Display.
echo $queryContent[ 0 ];
}
// Because $queryContent is now equal to FALSE, the loop
// will not be entered.
?>
The only solution to this is to reset the pointer to make it point at the first row again before the second code segment, so now the complete code will look as follows:
<?php
// Assume We Already Queried Our Database.
// Loop Through Result Set.
while( $queryContent = mysql_fetch_row( $queryResult ) {
// Display.
echo $queryContent[ 0 ];
}
// Reset Our Pointer.
mysql_data_seek( $queryResult );
// Loop Again.
while( $queryContent = mysql_fetch_row( $queryResult ) {
// Display.
echo $queryContent[ 0 ];
}
?>
Of course you would have to do extra checks to make sure that the number of rows in the result is not 0 or else mysql_data_seek itself will return false and an error will be raised.
Also please note that this applies to all functions that fetch result sets, including mysql_fetch_row, mysql_fetch_assos, and mysql_fetch_array.
When someone says you can't call mysql_fetch_assoc() twice, they mean against the same resource. The resource result you pass in to mysql_fetch_assoc() is done by reference. You'll need to reset the position of the pointer before you can use mysql_fetch_assoc() a second time.
EDIT: And to do so, try using mysql_data_seek().
It appears that what you want to do is to treat the query result as an array (rows) of arrays(fields). But that's not really what the mysql library provides. What I will often do is in fact copy the rows into an array of arrays (just loop on mysql_fetch until empty) and then do what I want with my own rowset using array functions that PHP provides for the purpose. This also minimizes the amount of time the table is locked.

Categories