How to reuse sql query result in PHP? - php

I'd like to do different operations on the data returned from a single sql query, something like this:
$sql = "SELECT * FROM mandant";
$res = pg_query($_db,$sql);
while ($mandant_list = pg_fetch_object($res))
{
# do stuff
}
while ($mandant = pg_fetch_object($res))
{
# do other stuff
}
But this doesn't work. The first loop gets the data, the second one not.
Is it possible to reuse the result returned from the query without running it again?
If not, why? What happens to the $res variable?

Yes, you can "rewind" the result resource by using pg_result_seek().

It is possible.
The reason the second loop breaks is because every time you are fetching a row from the data set it is being decremented until there are no rows left in the object.
You'll need to make 2 copies of $res and then run the second while() on the second $res.

Related

What make the difference in 2 ways of while loop "php mysql_fetch_array"?

When I do the following:
while($row = mysql_fetch_array(mysql_query($query))){}
it is infinitive while loop.
But this one is not:
$query = mysql_query($query);
while($row = mysql_fetch_array($query)){}
What is the difference between them? How does PHP execute?
Lets assume that you have a table student with following data
id name
1 JD
2 Dev
3 Pallavi
Now if your $query = "SELECT * FROM student"
CASE: 1
while($row = mysql_fetch_array(mysql_query($query))) { ... }
For the first iteration the execution will be
mysql_query($query)
mysql_fetch_array(get_array_obtined_from_first_step)
Assign the current row to $row
In first step you get all 3 records of the student table. Then you fetch the Record Set in 3rd step you assign the row to $row.
Now as your 3 statements are in the while loop's condition, it will always be TRUE, because it will execute your query each time the loop is iterated, executing all the statements, making it infinite loop.
CASE: 2
$query = mysql_query($query);
while($row = mysql_fetch_array($query)){}
Here the query is executed ONCE and then each time the cursor is incremented assigning a single row to $row till the end of Result Set.
Thus when the end of Result Set is achieved it stops.
Let's look for
while($row = mysql_fetch_array(mysql_query($query))){}
In this, sql query execution is in while loop, means it's recursion itself, hence every time $row will get new data means while loop will not end anywhere.
$query = mysql_query($query);
while($row = mysql_fetch_array($query)){}
In this case, you are executing query before while loop. Now you have specific set of result in your $query variable. $query has some limit like 0 or maximum record. Hence loop will stop execution at some point.
How a WHILE loop works:
You need to understand when while loop stops iteration. A while loop looks like this :
while (expression) {
statement
}
At the beginning it will evaluate the expression first, if it returns TRUE (or which is equivalent to TRUE), then it will execute the statements inside the {...} block, otherwise, it will not execute anything. After it has finished the execution of that part, it will evaluate the expression again. If it returns TRUE again, it will execute scripts again, otherwise, it will stop here. This cycle will continue until the expression returns FALSE.
Difference between two expressions:
Now just look at your expression blocks
mysql_fetch_array(mysql_query($query))
It will always return TRUE, because, it is every time running the mysql_query and mysql_query returning result every time and mysql_fetch_array is always able to fetch the first row, which allows the loop to execute the statement block every time. That's how it becomes an infinite loop.
$row = mysql_fetch_array($query)
Here you have run the query before (only once) and within the while expression you are fetching through the result. You get first row, 2nd row and so on every time you call mysql_fetch_array(). When you finish fetching the last row in the result set, mysql_fetch_array() will return FALSE, which will stop the iteration of while loop.
Recommended Readings:
http://php.net/manual/en/control-structures.while.php
http://php.net/manual/en/function.mysql-fetch-array.php
http://php.net/manual/en/function.mysql-query.php
Note : Consider switchig to mysqli_query() / mysqli_fetch_array() asap. The old functions are not going to be supported by PHP 7.
In the first one, PHP executes the query each time the loop enters new iteration, so the cursor (pointer to the row that goes forward each time you iterate over the result) does not move forward in the array of results. You get the whole bunch of same results each time and each time start from the beginning since the query is just executed.
In the second one your query is executed only once, and then PHP is iterating over the complete array of results while the cursor is moving forward and not being reset to zero on each iteration. That one is probably what you need.

php loops - while or do while?

I'm still very new to PHP and pgsql... new to coding in general.
I'm trying to figure out if I should do a while or do while loop on this problem.
I need to query a remote source for data and update my db, but I'm limited to the number of returns per call. I have over 1000 rows to update, but my call limit is 100. This means I need to do multiple calls until all rows in a column are no longer null.
I believe this is the right query, but is my while statement correct?
Here my code:
// $dbconn = connection......
$result = pg_query($dbconn, "WITH data(full_address) AS (VALUES ('location'))
SELECT full_address FROM $table WHERE latitude is NULL limit 5;");
while ($row = pg_num_rows($result > 0)) {
$arr = pg_fetch_all($row);
//curl commands fetch data and ingest
}
Use do while id the loop should get executed atleast once.
While is entry control loop(it will check condition while you are entering the loop)
Do While is exit control loop(it will check condition after executing the loop one time.)
If you want the loop to run at least once; use do, but if your loop might never be executed (because of the condition) then use while.
In your case, while is prefered since the database query might give no results. Your while loop needs to fetch a single row and process it until there are no more rows to fetch.
while ($row = pg_fetch_row($result)) {
//your code to use row's data
}
do-while loops are very similar to while loops, except the truth
expression is checked at the end of each iteration instead of in the
beginning. The main difference from regular while loops is that the
first iteration of a do-while loop is guaranteed to run (the truth
expression is only checked at the end of the iteration), whereas it
may not necessarily run with a regular while loop (the truth
expression is checked at the beginning of each iteration, if it
evaluates to FALSE right from the beginning, the loop execution would
end immediately).
from: http://php.net/manual/en/control-structures.do.while.php
EDIT
// $dbconn = connection......
for($=0;$i<10;$i++){
$result = pg_query($dbconn, "**your query with** Limit ".(100*$i).",100;");
while ($row = pg_fetch_row($result)) {
//your code to use row's data
// do your curl stuff here for the 1 result
}
}

PHP while() fails to stop looping

I was getting a problem because using while() function but I'm solving it for five or six hours today. I'm asking here because I don't understand how it could be.
Here is my code
$sql = mysql_query("SELECT saldo from stock where id >= '$id' and idItem = '$idItem';")
if I try :
$row = mysql_fetch_array($sql);
while($row)
{ // my code is here
}
then, while() fails to stop looping. but if I try like this:
while($row = mysql_fetch_array($sql))
{//my code is here
}
by that code, I'm getting the correct result.
I feel this is little strength because I think the first and the second code have same function.
thanks for you comments or answers!
mysql_fetch_array() fetches one row at once when you use in while it fetch next row every time. It returns true if there is any next row to fetch and false if there is not.
For preventing infinite loop, Use this is correct syntax for fetching:
while($row = mysql_fetch_array($sql))
{
//your code
}
Note: The original MySQL extension is now deprecated, and will generate E_DEPRECATED errors when connecting to a database. Instead,
use the MySQLi or PDO_MySQL extensions
$row is not affected by the loop, so of course it keeps looping. You probably want something like this:
while($row = mysql_fetch_array($sql))
{ // processing code goes here
}
In your first snippet, the loop condition is always true because the value of $row never changes and you're ending up in an infinite loop.
In the second snippet, $row is re-assigned upon each loop iteration and once it's null (usually at the end of the recordset in the case of mysql_fetch_array) the loop terminates.
Because first code uses same $row every time, the loop never stops and it doesn't even fetch the result per each iteration.
But the second code fetches result every time, the loop works as you expected.
The reason the second one eventually stops, is because every call to mysql_fetch_array() will call the next row from your database query. Once all the rows have been called, it will start returning false and this is what ends the loop.
It can be a little confusing because you're not seeing any counter, but the counter is really hidden inside the mysql_fetch_array() function, and will eventually terminate.
But if you put that call outside the while loop, it's only called once and you keep iterating the same row.
$row = mysql_fetch_array($sql);
while($row)
{ // my code is here
}
mysql_fetch_array fetches 1 and only 1 row from your table into $row, so if you have one row matching your query you dont need a while
if the resulting query has more than 1 row you need to make a while to the mysql_fetch_array like this:
while($row=myql_fetch_array($sql){}
now you can get all the rows from your table
The value of $row is not changed in the first case. You would need to update it again within the loop with another assignment, so your 2nd statement is better, as it does it all in one go :)
For -
$row = mysql_fetch_array($sql);
while($row)
{ // my code is here
}
$row is always true as it contains the values so the loop will be executed infinitely. And
while($row = mysql_fetch_array($sql))
{//my code is here
}
$row is ture untill the mysql_fetch_arrya has values.
mysql is deprecated. Try to use mysqli or PDO instead.
Try this code:
You have a semicolon inside your query.. your semicolon must be at the end of the mysql_query() function. That may be the cause of your infinite looping in while loop.
$sql = mysql_query("SELECT saldo FROM stock WHERE id >= '$id' AND idItem = '$idItem'");

how to print mysql result RESOURCE_ID(7) without mysql_fetch_array

Is there any way to print the resource_id without mysql_fetch_array.I dont want to loop through result.I want print only the first row at top.I know mysql has been depreciated.This is for old project.
You can make use of arrays in your case
$all_rows = array();
.
. // your query
.
while($dbrow = mysql_fetch_array($query))
{
$all_rows[] = $dbrow;
}
$first_row_array = $all_rows[0]; // first row will be stored here
/*
uncomment the below line if you do not want to use the
first row again while looping through the remaining
rows
*/
/* unset($all_rows[0]); */
foreach($first_row_array as $first_row)
{
// do something with first row data
}
foreach($all_rows as $dbrow)
{
// loop through all the rows returned including the first row
}
A resource in itself is a pretty meaningless type. It only means something to specific functions, like mysql_*. When querying the database, there are certain resources allocated on the MySQL server which hold your requested result; PHP doesn't really have access to those results yet. To give you a handle on those resources on the MySQL server, you get a resource type variable. It's basically just your ticket, saying "if you ever want to access that data waiting for you on the MySQL server, use this number."
So, if you want to output the data from the MySQL server, you will have to fetch it from there, e.g. with mysql_fetch_assoc. That then returns the data to you which you can print.
If you just want the first result, just call that function once.

Why does my code only return every second result in php mysql?

I have been writing some code which pulls entries from a MySQL database. These are numbers 1 to 38
However, it only returns every second number i.e. 2,4,6,8 instead of 1,2,3,4.
$result = mysql_query("select (caseID) FROM `case` order by caseID")
or die(mysql_error());
while(mysql_fetch_array( $result ))
{
$row = mysql_fetch_assoc($result);
$countName= $row['caseID'];
Print $countName;
}
I've tried various changes and reducing the code to the bare minimum. But nothing seems to work.
Calling mysql_fetch_array two times, thats why.
Try this
while($row=mysql_fetch_assoc( $result ))
{
$countName= $row['caseID'];
print $countName;
}
It is because you are calling mysql_fetch_array, which retrieves one result, and then you call mysql_fetch_assoc, which retrieves yet another result. That is then repeated until there are no more results left.
Or, in other words, you are fetching one result without using it, and then fetching another result which is then used, effectively jumping over every other result.
This should do the job:
while($row = mysql_fetch_assoc($result))
{
print $row['caseID'];
}
Also, take a look at the documentation. Turn your eyes to the big box that says "Warning" and has a stop sign in it.

Categories