PHP - Problem Using While Loop And Delaying With Sleep()
Hi,
I am trying to loop a script every 10 seconds but am getting the following error: Fatal error: Maximum execution time of 60 seconds exceeded Part of the code is: <?php while (1) { echo "hello"; sleep(10); ob_flush; flush(); } ?> I have put echo "hello" just to test before adding the script. Is there a correct way to do this loop? also running this the page struggles and says it is still loading. Similar TutorialsIn one of my servers when ever I call sleep or usleep functions my script sleeps and never wakes up, Any suggestion on what can cause the issue? my php -v output: Code: [Select] PHP 5.2.17 (cli) (built: Jan 24 2012 20:49:48) Copyright (c) 1997-2010 The PHP Group Zend Engine v2.2.0, Copyright (c) 1998-2010 Zend Technologies with the ionCube PHP Loader v4.0.12, Copyright (c) 2002-2011, by ionCube Ltd. I have this code: <html> <body> <?php echo date('h:i:s'), "<br>"; sleep(5); echo date('h:i:s'), "<br>"; echo "Your Pizza: ", $_POST["Pizza"]; echo " Has Been Sent To The Counter"; ?> </body> </html> which gives me this result:
07:41:06 I can't seem to get the page to sleep at all.
My intention is to achieve this a page that will display the message above for 5 seconds then run a relocation to the main page. but for now just making the page sleep would be of benefit.
any help would be appreciated. I am a beginner so I am expecting this to be something simple i have missed. I have a download page for my website and I tried using sleep to delay before the user can download an item. Right now I am using javascript to display a count down and the download link is in a hidden div and I wanted to have a time in php when the user goes to the page the timer starts and then echos the download link instead it being visible in the source code. <script> <!-- // var milisec=0 var seconds=30 document.counter.d2.value="30" function display(){ if (milisec<=0){ milisec=9 seconds-=1 } if (seconds<=-1){ milisec=0 seconds+=1 } else milisec-=1 document.counter.d2.value=seconds+"."+milisec setTimeout("display()",100) } display() --> </script> <div id="hid" style="visibility:hidden"><center><a href="upload/'.$row[4].'/'.$row[1].'"><img src="images/download.png" width="200" height="55" border="0" /></a></center></div> <script type="text/javascript"> function showIt() { document.getElementById("hid").style.visibility = "visible"; } setTimeout("showIt()", 30000); // after 1 sec </script> Hey all, I have a simple php script that whenever it is run (it is called x times per day from crontab) it sends out an sms to 10 people. Unfortunatelly the cell carrier has put a "delay" threshold of 30 seconds between sms that you can send in order to prevent sms spamming. The problem is that my script had a foreach loop that it just send out the sms to everyone so it took around 0.5-1 second for each sms.. Way to low for the 30 seconds that now are enforced. Do you have any ideas of what i can do to "force" my script to obey that 30 second delay between each sms? I thought of putting a cron job every 1 minute and send one by one the sms but wouldn't that be a problem to the server to have to execute 1440 times per day a script? I also thought of using some sleep function but i don't know if that would result in finally the script to output a success result after 10*30=300seconds(5mins).. Any ideas are appreciated! Well PHP manual says that the script execution will be delayed by $x seconds if you write a codes like this: Code: [Select] $x = 5; //5 secs sleep($x); Now I have this script in which I write the four lines to the screen one by one, each should be delayed by 5 secs after the last line is output to the screen. It does not work out at all... Code: [Select] echo "Update setting 1:"; sleep(5); echo "Success! <br>Updating setting 2"; sleep(5); echo "Success! <br>Updating setting 3"; sleep(5); echo "Success! <br>Updating setting 4"; Instead, the entire script execution is delayed by 15 secs, with all four lines output at the same time. Why is this happening? Is there a way to fix it? Please help... When you use the sleep function in a script, will the script resume from that exact spot? I guess what I need to know is will it break an upload to MySql database of a csv file or will the whole file be uploaded? Thank All Hi All, I'm new to PHP and I'm probably making a fundamental mistake somewhere, however, enough time wasted, I thought you might be able to shed some light on my problem. I basically have a php script running with nginx and fast_cgi. The whole script is just a large switch statement that does some matching against the request strings and returns a template rendered by Tenjin. It all works fine and it's quite performant based on a simple curl-loader test. The simple performance figures are taken from curl-loader and show 400 CAPS (Call Attempts Per Second). The test is 200 clients requesting the same url for 100 cycles. The problem arises when I introduce a "sleep" into the php code for 150 milliseconds, which is my basic idea of introducing latency to the system. The performance for the same test of 200 clients * 100 cycles produces 55 CAPS which is a huge drop in performance based on 150 millisecond delay. The sleep method used is "usleep" and I've also tried "time_nanosleep". I know there's not a huge amount of info there but based on performance figures above, is there something fundamental/trivial I'm missing or doing??? Are there any known issues with the sleep methods??? I've tried setting 'set_time_limit(0)' before the sleep call but that didn't help. Any advice you can offer is greatly appreciated.. I want the login script to echo out a statement, and then after 5 seconds (if the user hasn't clicked the link manually) I want it to redirect with the header redirect. I'm using the sleep function for the delay of the redirect. Here's the concerned portion of the login script: // check to see if the INPUT DATA matches the DATABASE COLUMNS! if ($nickname == $dbuser_name && sha1($password) == $dbuser_password) { // set a session after login $_SESSION['user_name'] = $dbuser_name; $_SESSION['user_id'] = $dbuser_id; echo "<center>You're logged in! <a href='01.php'>Click here</a> to go to the main page.</center>"; sleep(5); // seconds to wait header ('Location: 01.php'); // password incorrect error message } else { echo "<center>Incorrect password!</center>"; } But the echo statement never gets printed out, any idea why it gets swallowed by the sleep function? A WHILE loop in a FOR loop problem Script about links and sublinks from 1 table. In fact 2 questions about that. 1) In the FOR loop I have for example to do the loop 3 times. (needs to find 3 results withing the loop with if and else) When first time, he's gonna search within the WHILE loop that holds (for example) 10 records of the DB in a variable. He needs to search for rowid number 5, he found it He goes out of the WHILE loop and goes searching again but now for rowid number 2 Now it seem that the WHILE loop start searching for number 2 but won't start from his first row in the variable (10 rows from the db ). He start at row number 6 instead of beginning all over again !!! -> so the order of the numbers of rows MUST be in an ascending order, ortherwise he won't find them all ! But the numbers I have are NOT in an ascending order !!! Why doesn't the WHILE loop begin again from his row 1 in the variable ? FOR loop { WHILE loop { content here, break; } } 2) even when I get all the result in an ascending order, he won't go doing a second search but with a different rowid number that he gets from the FOR loop. It is giving me back indeed the right new rowid number, but the WHILE loop is doing nothing. I have put many echo "..."; and other stuff for checking but can't find the cause ! Here's the code : Code: [Select] // $ResultShow = 10 rows from mysql db if(isset($ResultShow)){ if (mysql_num_rows($ResultShow) >= 1){ //$linksuborder = "2,3,4"; $array1 = explode(",", $linksuborder); sort($array1); for ($n = 0; $n < count($array1); $n++){ // searchin for the right row id in the variable $ResultShow where we find the numbers for next loop $r1 = each($array1); While($Row2 = mysql_fetch_array($ResultShow)) { if($Row2["linkid"] == $r1['value']) // found it, now look for the numbers that we'll put in an array { echo "---here the content---"; // linksuborder is where numbers from row id's are stored like 5,2,8 //now put them in an array $array2 = explode(",", $Row2["linksuborder"]); sort($array2); for ($n2 = 0; $n2 < count($array2); $n2++){ $r2 = each($array2); ////// here searching for the sublinks ////// While ($Row3 = mysql_fetch_array($ResultShow)) { if($Row3["linkid"] == $r2['value']) // search for the right row id within the variable $ResultShow { echo "---here the content---"; break; // found it, so no need to do the rest of the loop } // end if } //end while ////// end searching for sublinks ////// } // end for } // end if else { echo "--- content here ---"; } } // end while } // end for } //end if } // end if Table : linkid linksuborder linktitle 1 2,3,4 2 9,7,8 mainlink1 3 10 mainlink2 4 mainlink3 5 6 7 sublink3 8 sublink2 9 sublink1 10 sublink4 -> linksuborder 2,3,4 are the row id's for the mainlink -> than we put the numbers 9,8,7 (also row id's) mentioned in row linkid 2 also in a new array -> now we can search for the sublinks -> get the details from row linkid 9, than 7, than 8 -> First mainlink is compleet, now go to row linkid 3 to do it all over again for the next mainlink... RESULTS from an sorted array -> sort($linksuborder); ------------------------------------------------------------- mainlink1 : sublink1, sublink2, sublink3 mainlink2 : **no result back but it should * mainlink 3 : **no result back but it should * This is the email verification script im using.. //email verify $activationKey = mt_rand() . mt_rand() . mt_rand() . mt_rand() . mt_rand(); $sql="INSERT INTO account_info (activation_key, status) VALUES ('$activationKey', 'verify')"; if (!mysql_query($sql)){ exit('Error: ' . mysql_error()); } else { //Send activation Email $to = $_POST['email']; $subject = "NarutoRPG.com Registration"; $message = "Welcome to our website! You, or someone using your email address, has completed registration at narutoRPG.com. You can complete registration by clicking the following link:\rhttp://www.arzania.com/verify.php?$activationKey\r\r If this is an error, ignore this email and you will be removed from our mailing list.\r\rRegards,\ narutoRPG.com Team"; $headers = 'From: ashyiscool2@gmail.com' . "\r\n" . 'Reply-To: ashyiscool2@gmail.com' . "\r\n" . 'X-Mailer: PHP/' . phpversion(); mail($to, $subject, $message, $headers); //User isn't registering, check verify code and change activation code to null, status to activated on success $queryString = $_SERVER['QUERY_STRING']; $query = "SELECT * FROM account_info"; $result = mysql_query($query) or die(mysql_error()); while($row = mysql_fetch_array($result)){ if ($queryString == $row["activation_key"]){ echo "Congratulations!" . " " . $row["username"] . " is now the proud new owner of a NarutoRPG.com account. Login to begin to play."; $sql="UPDATE account_info SET activation_key = '', status='activated' WHERE (id = $row[id])"; if (!mysql_query($sql)) { die('Error: ' . mysql_error()); } } } } } include "footer.php"; ?> For some reason, when the person is registered it shows everyones name who registered, for example.. You've been successfully registered!Congratulations! tonyhh is now the proud new owner of a NarutoRPG.com account. Login to begin to play.Congratulations! tonyh is now the proud new owner of a NarutoRPG.com account. Login to begin to play.Congratulations! tony is now the proud new owner of a NarutoRPG.com account. Login to begin to play.etc...etc.. How can you make it only repeat the users name who registered, not everyone? Hello, I have a loop below but the first time the person isn't counted in the if loop... I'm new to php and I know there is something easy I'm missing but I can't see it! Any help you be great. Code: [Select] // loop from mysql reults while($row = mysql_fetch_array( $result )) { echo "Person: ".$row['id']; echo "Earned: ".$row['earned']; //set-up php var's $earnedSum = $row['earned']; $firstPerson = $row['id']; if ($lastPerson == $firstPerson){ $earnedTotal = $earnedTotal + $earnedSum ; // Add's the earn units $lastPerson = $firstPerson; }else{ $earnedTotal = 0 ; // reset $lastPerson = $firstPerson; } echo 'This is the total Earned Result = '.$earnedTotal.'<br>'; } ?> All,
I am taking the output for every title in my Database and displaying it in a box. Within that box I am providing the opportunity to open another box with further content inside. The problem with the code below is that when you click on the expand button it expands in all the boxes, not just the one you are clicking in. I don't understand why this is happening when everything else is ok - any fixes and explanations are greatly appreciated:
// GOING THROUGH THE DATA if($result->num_rows > 0) { //echo "<hr />"; while($fetch=mysqli_fetch_array($result)) { $title=$fetch['title']; $feed_rss=$fetch['url']; $content_id=$fetch['content_id']; $source_image=$fetch['source_image']; $item_id = $fetch['item_id']; $item_title = $fetch['item_title']; $item_date = $fetch['fetch_date']; $item_description = $fetch['item_description']; $item_url = $fetch['item_url']; ///////////////////////////////////////////////////////////////////////////////// // ?> <div class="box col5"> <?php $query_string = "cid={$content_id}&t={$item_id}&item_title={$item_title}"; $url_query_string = "http://www.disciply.com/article/index.php?" . $query_string; /*Start of dynamic content open*/ echo "<p>$title</p>"; echo "<img src=$source_image />"; echo "<p>item_url = $item_url</p>"; ?> <div class="panel_button" style="display: visible;"><img src="../images/expand.png" alt="expand"/> <a href="#"><?php echo $item_title; ?></a></div> <div class="panel_button" id="hide_button" style="display: none;"><img src="../images/collapse.png" alt="collapse" /> <a href="#">Hide</a> <object type="text/html" data='<?php echo $item_url;?>' width="100%" height="800px" style="overflow:auto;border:5px ridge blue"> </object> </div> </div> Edited by genista, 19 July 2014 - 10:33 PM. Hi guys, I have this code which fetches data from an existing database and reflects the data into a tabular form. Basically what it does is it parses the field portNumber from my table and gets the last two digits of the variable. Then it will highlight in the table all those returned values for portNumber. Here is the code: Code: [Select] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Location Mapper</title> <script> function highlightRow(id) { document.getElementById(id).style.backgroundColor = "FFCC00"; } </script> <style> body { font-family:Tahoma, Geneva, sans-serif; font-size:10px; text-align:center; } .unitHere { color:#000; background-color:#0F0; styl } </style> </head> <body> <table width="800" border="1" align="center" cellpadding="0" cellspacing="0"> <tr> <th colspan="40" scope="col">SCMST 238</th> </tr> <tr> <?php $conn = mysql_connect("localhost", "root", "123456") or die(mysql_error()); mysql_select_db("orderstatus") or die(mysql_error()); $sql = mysql_query("SELECT * FROM superdome WHERE portNumber LIKE '%238%' AND isHistory='0' ORDER BY portNumber ASC") or die(mysql_error()); if(mysql_num_rows($sql) == 0) { echo "NOTHING FOUND"; } else { $i = 1; while ($i <= 40) { $x = 0; while($result = mysql_fetch_array($sql)) { $resultPortArray = str_split($result['portNumber'],4); $resultPortArray[1]; $x++; } if ($resultPortArray[1] == $i) { echo "<td width=\"20\" height=\"30\" id=\"".$i."\" class=\"unitHere\">".$i."</td>"; $i++; } else { echo "<td width=\"20\" height=\"30\" id=\"".$i."\">".$i."</td>"; $i++; } } } ?> </tr> </table> </body> </html> The problem is my output only highlights the one column in the array returned. The rest are not highlighted. I need help badly. hi The output of this code is: 1950 1951 1952 .... script Code: [Select] <?php for ($i = 1950; $i < 2012; $i++) { echo "<option value='$i' class='dr'>".$i.'</option>'; } ?> but i need something like: Insert a date 1950 1951 1952 .... how can i solve that? welll. i can do <option value='null' class='dr'> year</option> this foreach loop is causing mysql_num_rows to not return the amount of rows in mysql correctly. the variable $value has two strings in it (testa and testb). So foreach should loop once with $value as 'testa', then loop again with $value as 'testb'. the problem is at the mysql_num_rows. It should return 1 because there is 1 row in mysql with keywords 'testa' and 1 row with keywords 'testb', instead it returns zero. If i change $value to 'testa' it works. Code: [Select] foreach($value as $value) { $updatestable = mysql_query("SELECT * FROM `Stacks` WHERE keywords LIKE '%$value%' ORDER BY id DESC LIMIT 1")or die (mysql_error()); $upnum = mysql_num_rows($updatestable); echo $upnum; if ($upnum==0){ $uporigin=0; } else { while($rowup = mysql_fetch_assoc($updatestable)) { $uporigin = $rowup['origin']; $upreply = $rowup['reply']; } } } hope the question isn't too complicated. basically if i remove the loop. the mysql num_rows works and returns a row. If i don't remove the loop it returns zero. Hi Guys, I am trying update some array values in my database. For some reason using the code below the $checked and $counter values are not working. I have added the echos for debugging purposes and nothing is being echoed. $query = mysql_query("SELECT * FROM offers WHERE seller='$username' AND buyer='$buyer'"); while ($row = mysql_fetch_assoc($query)) { $checked = $_POST['checkbox'][$y]; $counter = $_POST['counter'][$y]; echo $checked; echo $counter; $date = date("Y-m-d"); $time = date("H:i:s"); mysql_query("UPDATE offers SET offer='$counter',seller_status='Counter Offer Made',buyer_status='Counter Offer Received',date='$date',time='$time',seller_action='0',buyer_action='1' WHERE domain='$checked'"); } When i do the following it echos the $checked and $counter values perfectly so i know that the form is posting ok. foreach ($_POST['checkbox'] as $checked) { echo $checked; } foreach ($_POST['counter'] as $counter) { echo $counter; } Can anybody figure out what is wrong with my while loop? Iv been at it for ages and cant seem to crack it. Thanks I am trying to loop through a filtered table. This is the code of the loop:
$result = mysqli_query($con,$sql);
$query = "INSERT INTO invoiceitems(invnumber,itemnum,price,quantity) VALUES('$ttinvno','$itemno','$price','$qty')";#,unix_timestamp())";
if ($prebidder != $buser) { } ?> The filtered data has 55 rows of which 28 are unique. I am trying to loop through so that the names ($buser) match the invoice number ($ttinvno). I have the rows indexed on buser descending. But the rows don't seem to want to match correctly. The invoice numbers go in sequence correctly but for instance the first two rows have the same name. But no matter what I have done in this format either the invoice number changes after the first row, or it changes after the third row. I want it to change after the second row. I have tried multiple ways including prematurely defining row and then using mysqli_data_seek($result,0); to reset the result before the loop. Obviously there is a flaw in my code. Can anyone help? Thanks very much in advance!
Hi! I have a code that don't do want I want that to do. <?php $chars = str_split('abc'); $char_len = count($chars); $length = 3; //loop for char_len^length $loop_length = pow($char_len, $length); for($i = 0; $i < $loop_length; $i++) { //convert $a to chars $string = ''; while($a != 0) { $string = $chars[$a % $char_len] . $string; $a = (int) ($a / $char_len); } //pad and print string echo str_pad($string, $length, $chars[0], STR_PAD_LEFT), "<br>\n"; if($loop_length-1 == $i){ $length++; } } ?> And what it do, is to print out all combination of a, b and c. My problem is that when the loop is done (you'll se my if statement) I want to add one on length so it print out a, b and c in four letters. ex abca, abcb. But it isen't working. Have you any clue that can help me? Thank you for your answer. |