I have one question about mysqli_fetch_assoc in a while loop.
$query = "SELECT * FROM category ";
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($result))
{
$cat_id = $row['cat_id'];
$cat_title = $row['cat_title'];
echo $cat_id . " " . $cat_title ."<br>";
}
So, how does $row = mysqli_fetch_assoc($result) work?
So it loops one row at a time from $results and stores that information in $row until it there is no row to return?
And this mysqli_fetch_assoc($result) in while loop iterations is this " array(some rows that it got from $result) "?
$row = mysqli_fetch_assoc($result) is same as $row = array(all rows from $result that are gathered by mysqli_fetch_assoc) ?
And that means $row is actually an array, and every time it loops the information is not overwriten by new instead it is added?
When using the mysqli_fetch_assoc() function, PHP is placing the data from the database into an associative array. You can then pull the data out of the array inside of the loop.
Since there is no incrementation to tell the loop when to stop, the while loop takes care of that. So you could read it like so:
While the mysqli_fetch_assoc() has more records, keep looping. When it runs out, stop.
Returns an associative array that corresponds to the fetched row or NULL if there are no more rows. - from PHP manual on mysqli_fetch_assoc()
Whenever you call get_result() or mysqli_query() you will receive a mysqli_result object. This object contains the data fetched from the MySQL database server. The data from SQL is returned to PHP in rows. The purpose of mysqli_fetch_assoc() is to fetch a row from this object and move an internal pointer to the next row. Next time you call this method on the same object it will fetch a second row and move the pointer to the next row. Once a pointer moves beyond the last row this function will keep on returning NULL.
The values in each of the returned arrays correspond to a single row from the MySQL result set. The values are stored as an associative array. Each key is a column name from the SQL.
The purpose of the while loop is to simply call the same function over and over again until it returns NULL.
Bear in mind that using while loop is not the best approach. It is better to simply use foreach.
$query = "SELECT * FROM category ";
$result = $connection->query($query);
foreach ($result as $row) {
$cat_id = $row['cat_id'];
$cat_title = $row['cat_title'];
echo $cat_id . " " . $cat_title ."<br>";
}
The simplest explanation is,
When you run mysqli_query() For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object which contains data from the database.
mysqli_fetch_assoc() - Fetch a result row(one row from the mysqli_result object) as an associative array at each time it called and moves the internal pointer to the next. $row is used to store that associative array containing data of single row getting from the mysqli_result object'
you can retrieve data belongs to that raw by using $row['column_name']
The while loop does the calling of mysqli_fetch_assoc() over and over. After one row is fetched, it goes to the next one and so on till it reaches the end of the object and returns NULL, which means false and breaks the while loop.
Related
I was messing around with how to do queries from MySQL and show them on PHP and I stumbled upon something:
This is the table I'm doing the query to:
$query = mysqli_query($conexion, "SELECT * FROM notas");
while($nota = mysqli_fetch_assoc($query)){
var_dump($nota);
echo $nota["Descripcion"];
}
Whenever I use a while() to display all the results of the query, it works. This table have 2 rows and both of them are showing.
Result of the var_dump($notas):
But whenever I use a foreach(), it just returns me the last result of the query.
$query = mysqli_query($conexion, "SELECT * FROM notas");
foreach(mysqli_fetch_assoc($query) as $valor){
var_dump($valor);
}
Result of the var_dump($valor):
Is there any reason why? I'm doing something wrong in the foreach() loop? I really can't tell. I would just say "fudge it", accept it and only use while loops to display queries, but, you know, want to know if I was doing something wrong or not understanding something.
The second version is looping through the columns, not the rows. It's equivalent to:
$row = mysqli_fetch_assoc($query);
foreach ($row as $valor) {
var_dump($valor);
}
You can see here that it's just fetching one row, which is an associative array, then looping through the elements of that array.
foreach (<expression> as <variable>) doesn't re-evaluate the expression every time through the loop. It executes it once, saves that array, then loops through the array elements.
The mysqli_result object is iterable, so you can do:
foreach($query as $valor) {
var_dump($valor);
}
You can also call mysqli_fetch_all($query), which will return a 2-dimensional array of all the results, and then loop through that. But if the query returns many results, this will use lots of memory.
This is probably a silly beginner question and i don't think it's limited to mysqli_fetch_assoc() so it's probably a general programming question.
Anyways, i have this PHP code for getting data from a database using mysqli
$sql = "SELECT name FROM table1";
$result = mysqli_query($conn, $sql);
if($result){
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
echo "Name: " . $row["name"]. "<br>";
}
}
}
What i don't understand is how the while loop there works. How does it iterates to the next element and know when to end? mysqli_fetch_assoc() returns a associative array which is stored in row variable which means it is not null therefore true and let's the while loop run. What i don't understand is how it iterates through the rows and ends when there are no more rows left. I'm not specifically doing anything to change the row to the next one so how does it do it on it's own?
Also mysqli_fetch_assoc() returns a associative array so shouldn't "name" key contain 1 element? Or is it a array of all the rows in that column?
(I hope you can understand what i'm trying to say, i'm not the best at explaining .-.)
Edit: What i don't understand is how this code iterates through all the rows. Is it part of the "inbuilt code" in this function? (I couldn't find it anywhere to confirm)
Each time when
mysqli_fetch_assoc($result) is accessed, the pointer moves to the next record. At last when no records are found, it returns null which breaks the while condition.
Eventually, when mysqli_fetch_assoc($result) runs out of rows it will return NULL, which evaluates to false, which breaks out of the loop.
$row results in a single row in the database, so $row['name'] would be the value of 'name' for a particular row.
Let's break it down, with perhaps a dumbed down example of how it works internally (Please note, this works a lot more efficiently, and wont actually run multiple queries):
$result = ['currentRow' => 0, 'query' => 'SELECT name FROM table1'];
while ($row = mysqli_fetch_result($result)) {
}
//First iteration
mysqli_fetch_result queries 'SELECT name FROM table1 LIMIT 0, 1'
it increments internally $result['currentRow'] to 1
it returns the row that was found
//Second iteration
mysqli_fetch_result queries 'SELECT name FROM table1 LIMIT 1, 1'
it increments internally $result['currentRow'] to 2
it returns the row that was found
//Third iteration
mysqli_fetch_result queries 'SELECT name FROM table1 LIMIT 2, 1'
no rows returned! Just simply return null (This will cause your while loop to break out)
You always pass $result as an argument to mysqli_fetch_assoc. This argument holds the iterator information, which will be used by mysqli_fetch_assoc to advance each time you call this function to the next row.
During each iteration, $row['name'] will be a single string.
I have found some PHP code that connects to a MySQL database and gets the column CityName for each row of the table Cities. I'm curious why while() loop is used and not for() or foreach. So here are my questions regarding how while() works in case of looping through arrays:
First, isn't $row variable an 2D array which it's rows contains the list of cities from the SQL query and it's columns contain the columns of each row of the query?
If this is the case, couldn't for() or foreach() be used to loop through the $row array?
Second, how does while() know when the array ends using only $row = $stmt->fetch_assoc() in the while()'s first line in order to end the loop?
Third, how does while() move to the next row of the $row array without using next() at the end of the loop?
And last but not least, how does echo $row['CityName']; output the city name of each row of the $row array without specifying the row of the array to use but only it's column CityName?
Thanks for any answers.
$query="SELECT CityName FROM Cities";
if($stmt = $connection->query("$query"))
{
while ($row = $stmt->fetch_assoc())
{
echo $row['CityName'];
}
}
else
{
echo $connection->error;
}
You could loop through $row, because it is an array (a simple array, not a 2d array); but you're not looping through an array called $row with the while, you're iterating over the resultset returned by $stmt->fetch_assoc() - which isn't an array- and assigning the value of a single returned row to $row in that statement (note the = for assignment) from the resultset.
while itself doesn't magically move any pointer; it's the call to $stmt->fetch_assoc() that not only returns a single row result, but moves the resultset pointer to the next result (and determines when it has reached the end of the resultset)
while($this_is_true){
// do this
}
# if the condition is not true for this while stmt, it will not execute (not even once)
do{
// stuff here
} while($thisIsTrue);
# even if the condition isn't true, a do-while executes at least once (the first time)
The point is that they are using a while() because it's a lazy way to say "only do it if it's true", so they don't have to check if it's true before they loop through it. WIth a for loop, you need to know the number of results you are looping through. For a do, you need to know that there are results before you attempt to use the results (echo). So, you use a while() to check if it's valid and then execute it, with just that piece of code.
Personally, I like to do...
if($query->num_rows > 0){
$query->bind_result($bindvar);
while($query->fetch()){
// do stuff
}
$query->close();
} else {
// no results found
}
You can use foreach instead of while. At least if stmt is a mysqli_result and you PHP version is not terribly outdated (newer than 5.4). In that case your loop would be:
foreach($stmt as $row)
{
echo $row['CityName'];
}
But this does not mean that $stmt is a 2D array. It's an object that implements the Traversable interface. That means that the foreach loop will implicitly invoke the required methods.
I have a simple MySQL query, I've checked the query in phpmyadmin and it returns 2 results.
I would like to put the result straight into a session variable which should be fairly easy, i have the code below and i only get the first result.
$row = mysql_fetch_assoc($get_data);
$_SESSION['data'] = $row;
In my head, this should put the result set into the $row variable, but it doesn't contain all the data. Would i need to wrap it in a loop?
Each time you call mysql_fetch_assoc it returns one row.
while($row = mysql_fetch_assoc($get_data)) {
$_SESSION['data'][] = $row;
}
Okay, so I realize that when do:
//connection code;
//query code;
//$result= mysqli_query();
$row= mysqli_fetch_array($result);
you create an associative array where the column names from your table are the keys for the data in the respective row.
Then you can use:
while ($row= mysqli_fetch_array($result))
{
//code to echo out table data.
}
My question is how does the while loop go to the next row after each iteration? I thought that was what foreach loops were for?
From http://www.php.net/manual/en/function.mysql-fetch-array.php
array mysql_fetch_array ( resource $result [, int $result_type = MYSQL_BOTH ] )
Returns an array that corresponds to the fetched row and moves the internal data pointer ahead.
Many functions that return a result set do so by returning an array that you can do a foreach() on like you are used to. This is not always the case however, especially with database functions. mysqli_fetch_array fetches just a single row, or returns boolean false if there are no more remaining. This is how the loop works: the expression evaluates to true as long as there is a row to process.
The reason for this construction is mainly efficiency. Fetching database rows can be a performance critical operation, and there are cases where not all rows are needed. In these situations this approach will give more flexibility. Fetching rows one-by-one is also more memory-friendly since not all result data will have to be loaded into memory at once.
Mysqli actually has a function that does fetch the entire result set in an array: mysqli_fetch_all. You will be able to foreach() over that.
mysql_fetch_array simply fetches the next row of the result set from your mysql query and returns the row as an array or false if there are no more rows to fetch.
The while loops continually pulls the results, one at a time from the result set and continues until mysql_fetch_array is false.
A foreach loop loops through each value of an array. As mysql_fetch_array only pulls one result and therefore the value of count($row) would be 1 every time.
Each time the while loop runs, it executes the function mysql_fetch_array and gets the next result. It does that until there aren't more results to show.
mysql_fetch_array returns an array of strings that corresponds to the fetched row, or FALSE if there are no more rows. If row exists then get data.
I hope this has answered you q. Its hard to understand what you mean
This part fetches one row at a time
$row = mysqli_fetch_array($result);
Putting it into a while loop makes it fetch one row at a time, until it does not fetch a row because there are no more to be fetched.
The alternative would be to fetch all the rows, then loop through them with a foreach
$rows = mysql_fetch_all($result);
foreach($rows as $row){
// do something with row
}
For this to work, you have to make yourself a mysql_fetch_all function, which of course has the original while loop in it...
function mysql_fetch_all($result)
{
$all = array();
while($thing = mysql_fetch_assoc($result)) {
$all[] = $thing;
}
return $all;
}
This works due to the SQL connector storing the current state of the query (i.e. the next result row to return) inside the result.
If you want a similar example, it works like reading from a file, where you're able to use similar constructs:
while ($line = fgets($fp, 1000)) {
// ...
}
Behind the scenes (and depending on the language, interpreter, compiler, etc.) for and while essentially result in the same code. The difference is, depending on what your code should do, one approach could be more readable than the other.
Take the following two loops as an example. Both do exactly the same.
for ($i = 0; $i < 10; $i++) {
// ...
}
$i = 0;
while ($i < 10) {
// ...
$i++;
}