mysql single returned value - php

I have a mysql query:
$a=mysql_query("SELECT id FROM table1 WHERE p2='fruit' LIMIT 1");
This will only ever return one result or none.
I'm trying to first count the results, then if it 1, to pass the returned id to a variable.
Question: If I do
$results=count(mysql_fetch_assoc($a));
to count the number of rows returned, can I still do later
while($row = mysql_fetch_array($a)){
$id=$row['id'];
}
or will the first delete the array somehow???
Is their a better way to do all this?

You really not need to do anything if there is one row or null
Consider below code it will set id value if there is 1 row fetched otherwise it will be null
$id=''
while($row = mysql_fetch_array($a)){
$id=$row['id'];
}
No count needed.

$results=count(mysql_fetch_assoc($a));
does not count the number of rows as mysql_fetch_assoc returns one row. I believe you're looking for mysql_num_rows:
$results = mysql_num_rows($a);

$num_rows = mysql_num_rows($a);
You can then do an IF statement on this and later do a while loop on the fetched array

Have you tried mysql_num_rows ??
http://php.net/manual/en/function.mysql-num-rows.php

What happens when using:
while($row = mysql_fetch_array($a)){
$id=$row['id'];
}
it is just like reading a file,every time mysql_fetch_array($a) is called the next line is parsed untill it reaches the end of the file. A cursor of some sort is known in the background. Meaning that if you would enter by hand
//backgroundCursor = 0
$row = mysql_fetch_array($a)
//backgroundCursor = 1
$row = mysql_fetch_array($a)
//backgroundCursor =2
$row = mysql_fetch_array($a)
//backgroundCursor = 3
The while instruction just automates the stuff.
mysql_fetch_array increases the background cursor at every call so if you call it twice it will not give you the same line.
To get a clear view on this read something about reading from a file line by line.

No you cannot as each call to mysql_fetch_assoc() loads a new row, if there is any. You could indeed assign both variables at once:
$results=count($row = mysql_fetch_assoc($a));
but
But mysql_fetch_assoc($a)) returns false and as the result of count(false) is 1 this will not tell you anything. Besides, if there is no row all you really need is $row = mysql_fetch_assoc($a) and test if ($row) {...}.

Related

How does while loop work with mysqli_fetch_assoc()?

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.

How to get next row of MySQL query in php without progressing when using mysqli_fetch_assoc()

I am trying to run a query to my mysql database through php and and am trying to get all the resulting rows. I also have to compare every row to the next row returned. I am trying to do this by setting the result variable to another temporary variable and calling mysqli_fetch_assoc() on that so that the while loop runs again for the next row. But what happens is that when I try to use mysqli_fetch_assoc() even on the other variables, somehow mysqli_fetch_assoc($result) also progresses to the next of the next row when while($row = mysqli_fetch_assoc($result)) goes to next iteration.
Here is the code example to illustrate this :
$query = "SELECT * FROM records ORDER BY num ASC;";
if($result = mysqli_query($conn, $query))
{
while($row = mysqli_fetch_assoc($result))
{
$temporaryresult = $result;
$rowtwo = mysqli_fetch_assoc($temporaryresult);// this makes mysqli_fetch_assoc($result) skip the next row which is unwanted
}
}
So how can I keep mysqli_fetch_assoc($result) from moving forward when I call mysqli_fetch_assoc($temporaryresult) ?
Any help would be appreciated.
am trying to do this by setting the result variable to another temporary variable and calling mysqli_fetch_assoc() on that so that the while loop runs again for the next row
It doesn’t work that way. Just because you assigned the resource id to a second variable, doesn’t mean that you now have a second result set that you could operate on separately. Both variables refer to the same resource id. Fetching a row will still move the row pointer of the “original” data set.
I also have to compare every row to the next row returned
Most likely, you are making things harder on yourself by trying to look ahead. Stuff like this is usually easier done when you look at the previous row instead. That one you have fetched already - so you don’t need to do an additional fetch now that would mess with the row pointer.
Pseudo code example:
$prevRow = null;
while($row = fetch(...)) {
if($prevRow) { // for the first row, this will still be null, so we only
// start comparing stuff when that is not the case
// compare whatever you need to compare here
}
...
$prevRow = $row;
}
After #CBroe's answer, I tried to solve this problem while still trying to look forward. I achieved this by storing the rows returned by the database and then looping through them. This makes it very easy too look ahead in the rows returned while avoiding the complexity of changing your code to look backwards.
$array = array();
// look through query
while($row = mysql_fetch_assoc($query)){
// add each row returned into an array
$array[] = $row;
}
Now, looping through these rows,
$i = 0;
for(;$i<count($array)-1;$i++)
{
if($array[$i]['somecolumn']==$array[$i+1]['anothercolumn'])//compare this column to another column in the next row
{
// do something
}
}
This successfully solved my problem. I hope it helps anyone stuck in the same position I was in.

MySQL result array into session variable

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;
}

Second while loop not running. Why?

I have two while loops running one after the other (not inside of each other) - I've simplified the code a bit so that only the important parts of it are listed below. The problem arises when I compare the two echoed queries because the 2nd while loop apparently isn't running at all.
I read somewhere that someone got around the problem by using a for loop for the second one but I want to get down to why exactly the second while loop is not running in my code.
$query_work_title = "SELECT title FROM works WHERE ";
while ($row = mysql_fetch_assoc($result_work_id)) {
$query_work_title .= "OR '$work_id' ";
}
echo $query_work_title;
echo '<br />';
$result_work_title = mysql_query($query_work_title) or
die(mysql_error($cn));
// retrieve the authors for each work in the following query
$query_author_id = "SELECT author_id FROM works_and_authors WHERE ";
while ($row = mysql_fetch_assoc($result_work_id)) {
$query_author_id .= "work_id = 'hello' ";
}
echo $query_author_id;
The MySQL extension keeps track of an internal row pointer for each result. It increments this pointer after each call to mysql_fetch_assoc(), and is what allows you to use a while loop without specifying when to stop. If you intend on looping through a result set more than once, you need to reset this internal row pointer back to 0.
To do this, you would mysql_data_seek() after the first loop:
while ($row = mysql_fetch_assoc($result_work_id)) {
$query_work_title .= "OR '$work_id' ";
}
mysql_data_seek($result_work_id, 0);
You've already looped through the result rows, so it's at the end and returns FALSE. (That's why it exited the loop the first time.)
To reset the internal pointer to the beginning of the result set, use mysql_data_seek().
mysql_data_seek($result_work_id, 0);
After the first while() loop completes, the internal pointer in the MySQL result is at the end of itself. You need to tell it to go back to the beginning using mysql_data_seek() between the first and second loops:
mysql_data_seek($result_work_id, 0);
You have already reached the end of your result set, but you can use mysql_data_seek to reset it.
// query your database
$result = mysql_query(...);
// loop through results
while(($row = mysql_fetch_assoc($result))) {
}
// reset result set
mysql_data_seek($result,0);
// loop again
while(($row = mysql_fetch_assoc($result))) {
}
According to your posted code, your SQL will look something like:
SELECT title FROM works WHERE OR '1'
That query will result in an error so your script shouldn't be getting past that point.
Even if it does, your second loop:
while ($row = mysql_fetch_assoc($result_work_id))
is using a result handle that has already been completely iterated by the first loop. By the the time the second loop tries to use it, mysql_fetch_assoc will return FALSE because there are no more rows to fetch. This will cause the second loop to exit immediately.
If both while loops need to access the same rows, combine their logic so the rows only need to be iterated over one time.
mysql_fetch_assoc steps through the results, right? It's already at the end on the second while loop, so it does nothing.

mysql_fetch_array() timing out

I am trying to query a database, but it seems to just load for an age and not do anything. It's a simple query and shouldnt take longer than a millisecond.
while($row = mysql_fetch_array(getWallPosts($userid)))
{
}
Now when I replace this code with:
echo mysql_num_rows(getWallPosts($userid));
It just displays '1' in fact there's only one record in the DB and it's just a simple SELECT statement.
Here's the getWallPosts function:
function getWallPosts($userid, $limit = "10")
{
$result = dbquery("SELECT * FROM commentpost
WHERE userID = ".$userid."
ORDER BY commentPostID DESC LIMIT 0, ".$limit);
return $result;
}
Also, when I put the SQL string that it's executing into MySQL's query browser. It takes no time at all.
Any ideas?
You appear to be looping indefinitely because you're retrieving a new set (one record) of data each time.
$result = getWallPosts($userid);
while ($row = mysql_fetch_array($result)) {
//printf($row[0]);
}
You need to get the data once and loop through it. Your code is getting the data, running the loop and then getting the data again.
Try:
$posts = getWallPosts($userid);
while($row = mysql_fetch_array($posts))
{
//Code to execute
}
Its an infinite loop. The expression in the while always executes so it will always be true.
You're returning a new result set each time the while statement executes. You should call getWallPosts first, assign it to $results, and then loop over it.

Categories