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
}
}
Related
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.
Assume I have this piece of code:
foreach($creds as $cred){
$prev_fut = $pdo->query("SELECT importo FROM incassi_prev WHERE
data_prev='$data_fut' AND incasso=0 AND
id_cre='{$cred['id_cre']}'")->fetch();
if(count($prev_fut)>0){
//I have found a result
}else{
//I have found nothing
}
}
NOTE: It is an internal query for my application with no data posted by user so I don't worry about SQL injections.
I use to check if count($prev_fut)>0 to see if the query is returning data (if I find any row in the db with these criterias).
My question is:
is this check enough to verify that the query has at least a result? Is it better to perform any other check?
The question is mostly coming from my thoughts about this being in a for loop and is related to the option of emptying/unset the $prev_fut array before starting a new iteration of for loop.
fetchColumn returns a single value of the next row in the result set. count counts the length of an array. Since fetchColumn can't return an array (for most database implementations), using count on it is wrong. You want to test whether $prev_fut is false or not. false would indicate that no result could be fetched, while anything else means a result was fetched:
if ($prev_fut !== false) ..
Having said that, you should really use a COUNT() in the database and check that value:
$result = $pdo->query('SELECT COUNT(*) FROM ...')->fetchColumn();
if ($result > 0) ..
It's much more efficient to have the database count and summarise the result than fetching an entire result set into PHP just for this simple check.
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'");
I'm not sure exactly what to search for to find my exact results. I am trying to create a system that retrieves data from database (no problem, this works). But I want to organize and minimize the amount of code for each section of the page. I am retrieving code via a MySQL query. I then set the $count = "0". Then I start my while statement $section = mysql_fetch_array($query) {
$count++ ...
Here is the tricky part: I want to do two if ($count > 0) statements. First, I want to say that IF $count > 0, echo table and headers for the table columns. I don't want this to repeat inside the while statement. I want this to only appear once. Basically, excluding this from the loop, but still be inside the while statement, because I don't want two while statements if at all possible.
The second if $count > 0 will then start echoing out each row result.
Not sure If I'm just being dumb and this isn't possible. It's something I've wondered about for a while now. I hope you understand what I'm looking for and didn't waste your time.
if (mysql_num_rows($result) > 0) {
// print headers
while ( $row = mysql_fetch_row($result)) {
// display row
}
}
what you could do, is alter your query, so that it retrieves the number of returned rows as well, using the included Count() function.
Then, before the while loop starts, you retrive this value from your Resultset and if it is > 0 you print your table headers and enter the loop.
Hope this helps.
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.