PHP question regarding a while statement for a loop - php

I asked someone to code up a loop for me, although I asked for the loop to run constantly as it should be doing checks. Say I wanted it to run for 2 hours in a loop.
They created this;
$result = select_query ('tbltest', 'id,userid,test');
while ($data = mysql_fetch_array ($result))
{
$userid = $data['userid'];
$id = $data['id'];
$test = $data['test'];
}
I don't know much about PHP, but it seems to me that once there are no more rows to go through and place in an array, it will end the loop.
How can I go about fetching the rows, but continuing in a loop for the next 2 hours?
Thanks!

I have no idea why you want to continue looping for 2 hours and doing nothing, but here's a solution (albeit a stupid one, if it serves your purpose):
set_time_limit(0);
$time = time();
while (time()<$time+7200)
{
if ($data = mysql_fetch_array ($result))
{
$userid = $data['userid'];
$id = $data['id'];
$test = $data['test'];
}
sleep(1); // so PHP doesn't consume too much resources
}

If you want to check something for a set amount of time, you should setup a cronjob to run a PHP script every X minutes rather than have a PHP script looping continuously.

you can't. when you do the select_query it actually returns a pointer of the full resultset as of that moment. the $data = mysql_fetch_array ($result) can only iterate over that values that were present in the resultset at the time of the initial select_query ('tbltest', 'id,userid,test');
call.. not to mention that I can't think of any properly configured PHP server that's going to let you leave a script running for 2 hours without timing out. perhaps what you want is a front-page with a AJAX script that re-checks the database for you in a loop. so that you would have your $.GET, and on the successfull return of your data you'd fire off another $.GET...

Can't you put the original database query inside stillstanding's loop?
set_time_limit(0);
$time = time();
while (time()<$time+7200)
{
$result = select_query ('tbltest', 'id,userid,test');
if ($data = mysql_fetch_array ($result))
{
$userid = $data['userid'];
$id = $data['id'];
$test = $data['test'];
}
sleep(1); // so PHP doesn't consume too much resources
}

Related

PHP error while getting multiple rows

I am trying to get all rows in database. My code:
$sql = "SELECT * FROM lectors";
$array = array();
while($row = mysqli_fetch_assoc(mysqli_query($con,$sql))){
echo $row["name"];
}
While I send request, server doesn't reply. Any ideas?
while($row = mysqli_fetch_assoc(mysqli_query($con,$sql))){
This is a never ending loop, your query will execute fine every time and loop will never terminate.
Need I say further?
It is only as good as
while(true)
{
// keep querying my database until i run out of resources
}
Execute the query first and loop over its result only.
And Oh,
While I send request, server doesn't reply
Because, as i said; It is busy running in a circle, has no time to reply.
Try to put the query in a line by itself, such as...
$sql = "SELECT * FROM lectors";
$array = array();
$res = mysqli_query($con,$sql);
while($row = mysqli_fetch_assoc($res)){
echo $row["name"];
}
Doing it in the method you are above will result in each execution of the loop executing the database query.

Long polling JQUERY chat using sleep()

The following code makes the web loading for like 10 minutes and I dont know why!
function chatheartbeat(){
include("config.php");
$useradn = $_SESSION['displayname'];
$query = "select * from chat where (userbdn = '".$useradn."' AND isread = 1) order by id ASC";
$result = mysql_query($query , $link);
$num_rows = mysql_num_rows($result);
if ($num_rows >= 1) {
$items = array();
$i='1';
while($chat = mysql_fetch_array($result)){
$items[$i]['from']=$chat['useradn'];
$items[$i]['msg']=$chat['msg'];
$items[$i]['timee']=date("H:i" ,$chat['timee']);
$i++;
}
$query = "update chat set isread = 0 where userbdn = '".$useradn."' and isread = 1";
mysql_query($query , $link);
header('Content-type: application/json');
echo json_encode($items);
exit;
}else{
sleep(2);
chatheartbeat();
}
}
Any suggestions?
The function will never return until there are some results from the first select.
I would suggest that you return after n runs through (e.g. 5), even if there are no results. The client can then re-issue the ajax call to poll again.
Also, it's not a great idea to do this in a recursive manner. I would suggest doing this in a for loop instead.
You are calling your function recursively and as the session variable does not change between the function calls, if it goes to the else part the first time, it will go there every time, creating a never ending loop.
By the way, if you want to use polling, you should set a timer in the client part (javascript) and not use a recursive function on the server side.
There are a few things you want to look at when performing any long polling techniques.
You need to exit after some predefined time period. Waiting on the server until you have something to respond with will lead you to execution timeouts.
Know what is going on with your SESSION data. PHP by default will use file based sessions and locks the file during the course of the request (unless you intervine)

How to perform a function for every row in a mysql array?

UPDATE: I solved it using a for loop:
for ($i=0; $i < mysql_num_rows($result); $i++) {
$row = mysql_fetch_assoc($result);
echo $row['name'];
}
ORIGINAL QUESTION:
This looks kinda stupid. I'm sure im missing something that's very simple, since I was able to accomplish this before. Anyways, I want to echo some text for every item in an array. This array is derived from mySQL.
here's the code
while ($row = mysql_fetch_assoc(mysql_query("SELECT * FROM files"))) {
echo $row['name'];
}
can you post the complete code? I think you forgot the database connection.
Try this:
$result = mysql_query("SELECT * FROM files") or die (mysql_error());
while ($row = mysql_fetch_assoc($result)) {
var_dump($row['name']);
}
This will throw an error, I guess you made a mistake over there. Also, var_dump() your $row in the while to make 100% sure you have "a" value.
Also, are you sure the row does exist? If don't have any records, the echo on your $row will not work sinc it does not exist.
Also, set error reporting to E_ALL like so.
error_reporting(E_ALL);
Also, since you are running your query inside the while() loop, it will continue to run forever. So first run the query, and put it in a variable, and then loop through the results. (see my piece of code above)
You can execute query individual instead of while loop because if your query return more than 1 rows it will goes under the loop. show your loop print only first data of result and your loop is infinite.
From your question it seems so simple, try this way it's working.
$sql="SELECT name From files";
$names = $db->query($sql);
while($name1 = $db->fetchByAssoc($names))
{
echo $name1['name'];
}

Running while($row = sqlsrv_fetch_array($result)) multiple times

I am retrieving a couple of tables from a MSSQL database, which I am then running through to obtain order information from.
My code looks like this:
while($row = sqlsrv_fetch_array($orderResult))
{
......code........
..................
while($statusRow = sqlsrv_fetch_array($statusResult))
{
....code....
}
....code....
}
Now my problem is that after the second loop runs through, it never runs again. And I need it to run every time the first loop runs.
Is there anything I can do to reset that second loop to run again?
Thank you in advance. Any help or a push in the right direction will be very helpful.
Read about the other parameters in sqlsrv_fetch_array()
You can do something like this to reset
// reset, and get first row
$row = sqlsrv_fetch_row($result, SQLSRV_FETCH_BOTH, SQLSRV_SCROLL_FIRST);
// get second (and nth row) normally
$row = sqlsrv_fetch_row($result);
Alternatively, I think you could benefit from doing a JOIN in your query to return a single result. Merging results manually like this seems a little hackish.
I had a similar problem when calling a stored proc from a database that returned multiple result sets. I found Macek's answer didn't work for me, but another answer did:
$resultSet = array();
$isNotLastResult = true;
$i = 0;
while (!is_null($isNotLastResult))
{
$resultSet[$i] = array();
while ($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC))
{
$resultSet[$i][] = $row;
}
$isNotLastResult = sqlsrv_next_result($result);
$i++;
}
print_r($resultSet);
PS: I gave you an up arrow to counteract your down arrow. You asked a question I spent quite a bit of time looking for the answer to. Good question!
Use the following to reset the pointer:
sqlsrv_fetch_array ($Res, SQLSRV_FETCH_ASSOC, SQLSRV_SCROLL_ABSOLUTE, -1);
Then use the same code as before to loop through the result set. sql_fetch_array appears to increment the pointer after retrieving the data. Requesting the -1 record retrieves nothing but then sets the pointer to 0 which is the first record.
are you sure your second loop got results for a second run ? maybe, if your $statusResult depents on your $row and your $row has just entries for the first loop you should insert some pseudo-entries to your db.
the second loop should refresh itself in the next "big" loop cause the whole inner block will be destroyed at the end of the big block and will be (fully) rebuild at the next entry.

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