PHP - Can't Echo In Real Time Under A Foreach Loop
I wrote a short script that takes a list of keywords and does a Google search to find how often they are used in the title of a page. However, I cannot get it to echo the results in real time. On one server I use it works fine. On the other it runs the entire list and then outputs everything in the end. The problem is sometimes this takes several minutes and therefore it times out after not receiving a response.
Any suggestions? Thanks in advance. <?php $file = file('words.txt'); $results = ''; foreach ($file as $line) { $data = file_get_contents("http://www.google.com/search?hl=en&q=allintitle%3A%22" . urlencode($line) . "%22&btnG=Google+Search"); preg_match('/of about <b>([0-9,]*)?<\/b>/si', $data, $number); $results .= $line . ";" . $number[1]; echo $results . "</br>"; $results = ""; sleep(2); } ?> Similar Tutorialsmy output is this below: Course: INFO101 - Bsc Information Communication Technology Course Mark: Course: INFO101 - Bsc Information Communication Technology Course Mark: Module: CHI2550 - Modern Database Applications Module Mark: 41 Mark Percentage: 68 Grade: B Session: AAB Session Mark: 72 Session Weight Contribution 20% Session: AAE Session Mark: 67 Session Weight Contribution 40% Module: CHI2513 - Systems Strategy Module Mark: 31 Mark Percentage: 62 Grade: B Session: AAD Session Mark: 61 Session Weight Contribution 50% As it shows 2 different Modules, it shows the "Course" details twice, I only want the "Course" details appear once as you can see both course details are the same. How can I display the "Course" Details only once in the foreach loop. To display the "Course" details I use this code: echo Code: [Select] `"<p><br><strong>Course:</strong> {$courseId} - {$courseName} <strong>Course Mark:</strong></p><br>\n";` Below is the code for the function and foreach loop: Code: [Select] function outputModule($courseId, $courseName, $moduleId, $moduleName, $sessionData) { if(!count($sessionData)) { return false; } $markTotal = 0; $markGrade = 0; $weightSession = 0; $courseTotal = 0; $grade = ""; $sessionsHTML = ""; foreach($sessionData as $session) { $sessionsHTML .= "<p><strong>Session:</strong> {$session['SessionId']} <strong>Session Mark:</strong> {$session['Mark']}</strong> <strong>Session Weight Contribution</strong> {$session['SessionWeight']}%</p>\n"; $markTotal += round($session['Mark'] / 100 * $session['SessionWeight']); $weightSession += ($session['SessionWeight']); $markGrade = round($markTotal / $weightSession * 100); if ($markGrade >= 70) { $grade = "A"; } else if ($markGrade >= 60 && $markGrade <= 69) { $grade = "B"; } else if ($markGrade >= 50 && $markGrade <= 59) { $grade = "C"; } else if ($markGrade >= 40 && $markGrade <= 49) { $grade = "D"; } else if ($markGrade >= 30 && $markGrade <= 39) { $grade = "E"; } else if ($markGrade >= 0 && $markGrade <= 29) { $grade = "F"; } } echo "<p><br><strong>Course:</strong> {$courseId} - {$courseName} <strong>Course Mark:</strong></p><br>\n"; $moduleHTML = "<p><strong>Module:</strong> {$moduleId} - {$moduleName} <strong>Module Mark:</strong> {$markTotal} <strong>Mark Percentage:</strong> {$markGrade} <strong>Grade:</strong> {$grade} </p>\n"; return $moduleHTML . $sessionsHTML; } Ok so I have a question. is it possible to make a form submit to a DB in real time without the need for a submit button ? if so could you drop a hint to what it would be caled or a tut / reference to it ? Hi guys, got some questions about the Instagram real-time api. first let me tell you what I want to do. I'd like to run a daemon process with a socket connection or something of the like to the Instagram API to get a constant feed of photos with a certain tag. We estimate it to be a large amount of data at a particular time (thus why we want to go Real-time). This process will parse the feed and store it into a mongodb database. Secondly, for the front end, I'd like to display all new, live photos in real-time, possible with ajax or some form of checking on a set interval. Problem being, I can't find anyone doing this with php. All of the resources I have seen use Node.js and Tornado. Has anyone done this with PHP or know of a good Real-time API demonstration/tutorial to get me started? Here's the documentation... http://instagr.am/developer/realtime/ any help would be greatly appreciated! thanks! Below is my output on the browser: Student: Kevin Smith (u0867587) Course: INFO101 - Bsc Information Communication Technology Course Mark 70 Grade Year: 3 Module: CHI2550 - Modern Database Applications Module Mark: 41 Mark Percentage: 68 Grade: B Session: AAB Session Mark: 72 Session Weight Contribution 20% Session: AAE Session Mark: 67 Session Weight Contribution 40% Module: CHI2513 - Systems Strategy Module Mark: 31 Mark Percentage: 62 Grade: B Session: AAD Session Mark: 61 Session Weight Contribution 50% Now where it says course mark above it says 70. This is incorrect as it should be 65 (The average between the module marks percentage should be 65 in the example above) but for some stange reason I can get the answer 65. I have a variable called $courseMark and that does the calculation. Now if the $courseMark is echo outside the where loop, then it will equal 65 but if it is put in while loop where I want the variable to be displayed, then it adds up to 70. Why does it do this. Below is the code: Code: [Select] $sessionMark = 0; $sessionWeight = 0; $courseMark = 0; $output = ""; $studentId = false; $courseId = false; $moduleId = false; while ($row = mysql_fetch_array($result)) { $sessionMark += round($row['Mark'] / 100 * $row['SessionWeight']); $sessionWeight += ($row['SessionWeight']); $courseMark = ($sessionMark / $sessionWeight * 100); if($studentId != $row['StudentUsername']) { //Student has changed $studentId = $row['StudentUsername']; $output .= "<p><strong>Student:</strong> {$row['StudentForename']} {$row['StudentSurname']} ({$row['StudentUsername']})\n"; } if($courseId != $row['CourseId']) { //Course has changed $courseId = $row['CourseId']; $output .= "<br><strong>Course:</strong> {$row['CourseId']} - {$row['CourseName']} <strong>Course Mark</strong>" round($courseMark) "<strong>Grade</strong> <br><strong>Year:</strong> {$row['Year']}</p>\n"; } if($moduleId != $row['ModuleId']) { //Module has changed if(isset($sessionsAry)) //Don't run function for first record { //Get output for last module and sessions $output .= outputModule($moduleId, $moduleName, $sessionsAry); } //Reset sessions data array and Set values for new module $sessionsAry = array(); $moduleId = $row['ModuleId']; $moduleName = $row['ModuleName']; } //Add session data to array for current module $sessionsAry[] = array('SessionId'=>$row['SessionId'], 'Mark'=>$row['Mark'], 'SessionWeight'=>$row['SessionWeight']); } //Get output for last module $output .= outputModule($moduleId, $moduleName, $sessionsAry); //Display the output echo $output; I think the problem is that it is outputting the answer of the calculation only for the first session mark. How in the while loop can I do it so it doesn't display it for the first mark only but for all the session marks so that it ends up showing the correct answer 65 and not 72? Hi, i am thinking of creating a text based game mmorpg using php/mysql etc... I know that a lot of these types of games use a tick based system, but i want it to be realtime, the only game i cna find that uses this is Torn, does anyone know how they make it realtime? I know that ticks can be controlled by cronjobs, but how about realtime? The problem is that the game might involve the player building a house, in a tick based system it could be easy to manage by saying the house will take 3 ticks to complete, but i want the house to be like in 10 minutes of 32 minutes, how can i do this. Someone said to check whenever the player next logs in to check if the house has finished and then say it has been built, but seeing as it is an mmorpg it could affect everyones gameplay, not just the person building it, so this will not work. Thanks and sorry if this is a bit confusing. Hi. How to implement twitter like real-time sharing system? So that is like, if my friend(following person) write a message, it also appear on my wall(page). 1. Is it hard? 2. What language used for it? PHP? 3. Is there any source about it? Thanks. I'm working on a chat using basic textarea input, post, but the problem that I'm facing is, if a person doesn't send something, then the output is not updated eg. other messages from other users updating in real time.
How is that achieved when you see new database entries pop up live, milliseconds after they are entered?
Do I set a constant refresh rate of some sort?
How do you update a section of a webpage without "refreshing" the entire page like the POST method?
I'm not looking for code, mostly just some direction, but I'm sure I'll be back as I try to shape the code. Also, I know very little about coding jQuery, Ajax, etc. Here is what I'm looking for: Basketball coach enters a Page that only he (or admin) can see. (I have that part figured out.) Once there, he has a form to fill out with a player's name and other information. I'd rather there not be 12 rows of empty cells. (Coaches will view that as work) I'd rather not have the Page reload on each "Add", but that would be the lesser of two evils. Is there a way to keep a persistent connection so when a coach hits Add, the player gets added to the database, a new empty form shows up, and the player's information shows up below on a roster? This topic has been moved to Editor Help (Dreamweaver, Zend, etc). http://www.phpfreaks.com/forums/index.php?topic=322054.0 Hey Guys! I have the following doubt. When echoing from Server like this: Code: [Select] echo "time=" . time(); I get the time in the following raw format: 1299272294 I would really like to echo it with this format: Tue Mar 1 23:50:00 GMT-0300 2011 Is there a way I could do that? Really looking forward for some help on this one, Thanks a lot in advance! Cheers! Hey guys, Got another question im hoping someone can help me with. I have a foreach loop (for use in a mysql query): foreach ($interests as $interest) { $query .= "($id, $interest), "; } problem is i do not want the comma(,) in the last loop. Is there some kinda of function i can use so it does not insert it on last loop? Or should i just use a for loop with a nested if loop? something like ; for($i=0; $i < count($interests); $i++){ $query .= "($id, '$interests[$i]')"; if($i + 1 < count($interests)) { $query .= ", "; } } Cheers guys Does anybody know how to make the following code correct? real sorry but its just absolutely blowing my mind im awful with loops and have pretty much no clue what the hell im doing in honesty, any help would be great, Thanks Code: [Select] $addIDs_ary = array_map('intval', $_POST['chkInv']); $addIDs_ary = array_filter($addIDs_ary); $value = $addIDs_ary; //Check if hit_id is already in hitlist $query = mysql_query("SELECT * FROM hitlist WHERE player_id = '$playerID'"); $result = mysql_query($query); while ($result = mysql_fetch_assoc($result)) foreach ($result as $hit_id => $value){ if($result[$hit_id] == $value); $str = ""; } } else what im trying to do is echo all of the results from the database query but add bold to results with a pid of 0. here is my code: $list = ''; $query = $link->query("SELECT * FROM ".TBL_PREFIX."forums ORDER BY f_lid ASC"); $result = $query->fetchAll(); foreach($result as $key => $val) { if($result[$key]['f_pid'] == 0) { $list .= '<b>'.$result[$key]['f_name'].'</b><br />'; } $list .= $result[$key]['f_name'].'<br />'; } echo $list; this works fine but the ones with a pid of 0 are displayed twice. once as bold and then once normal like so: General General New Features Testing Testing Sandbox Bugs my question is how to prevent this. For some reason I'm getting an invalid argument supplied for foreach error and I'm not sure why. Code: [Select] <?php // Include the database page require ('../inc/dbconfig.php'); if (isset($_POST['edit_event_lineup'])) { $event_items = $_POST['event_items']; $event_id = (int)$_POST['event_id']; foreach ($event_items as $items) { print_r($items); $segment_writer_id = (int)$_POST['segment_writer_id']; $introduction = mysqli_real_escape_string($dbc, $_POST['introduction']); $conclusion = mysqli_real_escape_string($dbc, $_POST['conclusion']); $segment_type = mysqli_real_escape_string($dbc, $_POST['segment_type']); $match_number = (int)$_POST['match_number']; $segment_number = (int)$_POST['segment_number']; $match_type_id = (int)$_POST['match_type_id']; $segment_title = mysqli_real_escape_string($dbc, $_POST['segment_title']); $match_type_id = mysqli_real_escape_string($dbc, $_POST['match_type_id']); $titles_id_list = mysqli_real_escape_string($dbc, $_POST['titles_id_list']); $stipulations_id_list = mysqli_real_escape_string($dbc, $_POST['stipulations_id_list']); $characters_id_list = mysqli_real_escape_string($dbc, $_POST['character_id_list']); $preview = mysqli_real_escape_string($dbc, $_POST['preview']); } $query = "INSERT INTO `event_segments` (event_id, segment_writer_id, segment_type, sort_order_preview, segment_title, preview, is_submitted_yes_or_no_id) VALUES ('".$event_id."', '".$match_writer_id."', '".$segment_type."' ,'".$sort_order_preview."','".$segment_title."','".$preview."',2)"; mysqli_query($dbc, $query); } ?> I have a foreach loop which shows the breadcrumb display. But it's stopped working. For some reason the links are no longer links. They are just echoed on screen with no <a> tags. setting up array: $crumb_query = mysqli_query($link, "SELECT f.forum_id, f.forum_cat_id, f.forum_name, c.cat_id, c.cat_name FROM ".TBL_PREFIX."forums as f LEFT JOIN ".TBL_PREFIX."categories as c ON c.cat_id = f.forum_cat_id WHERE f.forum_id = '$forum_id' ") or die(mysqli_error($link)); $crumb_info = mysqli_fetch_array($crumb_query, MYSQLI_ASSOC); $crumbs = array("index.php" => "Board Index", "./view_category.php?cid={$crumb_info['cat_id']}" => $crumb_info['cat_name'], "./view_topics.php?fid=$forum_id" => $crumb_info['forum_name']); echo build_crumbs($crumbs); the function: function build_crumbs($crumbs) { foreach($crumbs as $key => $value) { $crumb_display = "<a href=\"{$key}\">{$value}</a>"; $crumb_display = implode(" - ", $crumbs); } return $crumb_display; } can anyone see where im going wrong? how do I echo "blah" after the first loop in a foreach loop and the in the rest of them echo "crazy"? Hey guys, need help on some addition. foreach($login as $line_num => $line) { $login = explode(" ", htmlspecialchars(str_replace(" "," ",$line))); if(stristr($login[1], "\n")) $login[1] = substr($login[1], 0, strlen($login[1])-2); $account_data[$line_num] = array($login[0], $login[1]); $UserID = $login[0]; $AuthKey = $login[1]; $MobLink = "http://mobsters-fb-apache-dynamic-lb.playdom.com/mob_fb/"; $RefreshStat = file_get_contents($MobLink."refresh_stat_manual?user_id=".$UserID."&auth_key=".$AuthKey); $Cash = explode ("<cash>", $RefreshStat); $Cash = explode ("<", $Cash[1]); $Cash = $Cash[0]; $CashForEcho = "$".number_format($Cash[0]); echo $CashForEcho."<br/>"; echo "<br/><br/>"; } The variable $Cash will be dynamic for each user I put in the $login_file, and I need to add all of those values up. So say I put in 3 users within the $login_file, and the $Cash for user 1 was $3,000, the $cash for user 2 was $6,000 and the $cash for user 3 was $1,000, I want to be able to automatically add them all up, so it would echo '$10,000' at the end. Hope I've explained it for you guys to understand easily enough, if not let me know. Thanks I am working on a photo gallery script in which I need to show 9 images at a time. Here is my script so far Code: [Select] <?php foreach($pictures->result() as $p): ?> <?php for($i = 1; $i <= 9; $i++) { ?> <div class="item"> <ul> <li><a href="images/gallery/<?=$p->category;?>/<?=$p->photo_name;?>" rel="example1" ><img src="images/gallery/<?=$p->category;?>/thumb_<?=$p->photo_name;?>" alt="#" /></a></li> </ul> </div><!-- end item --> <?php } ?> <?php endforeach; ?> At the moment the script is showing one image at a time 9 times and for every entry in my database. I have been battling this for a little while now. Thanks in advance for all of your help! Hello, I am building an online game(users make a character and move on a map and so on...)
All user data is stored in a mySQL database and I want the users to interact in real-time, but there can be a 1-3 second delay between the communication, but not exceed 3 seconds even if 500 players are playing at the same time.
But for the purpose of the question let's say the users can only chat between one another, if I'll have a solution for that then I can use the same method for more parts of the game.
I can't use websockets because my webhost doesn't support it( I don't want to use pusher.com).
I know I can make real-time apps with ajax long polling, but I think that with 500 players playing at the same time it's not the best solution.
So, finally:
How can I make user interaction as close as possible to a real-time game?
(Without too much load on the hosting server)
(I am sorry if some of my terms are not correct - I am just getting back to coding after a long time...)
Edited by Mythion, 17 August 2014 - 02:34 AM. Hiya! I have an issue, here is my code. <?php class generateInvoice { private $invoiceID; public function __construct($invoiceID) { $this->_INID = mysql_real_escape_string($invoiceID); } public function __drawInvoice() { $get_invoice = "SELECT * FROM `invoices` WHERE `id` = '$this->_INID' LIMIT 1"; $run_get_invoice = mysql_query($get_invoice); if($run_get_invoice) { if(mysql_num_rows($run_get_invoice) == 1) { while($invoice_m = mysql_fetch_assoc($run_get_invoice)) { if($invoice_m == 1) { $status = 'Awaiting Payment'; } elseif($invoice_m == 2) { $status = 'Paid'; } $items_mass = explode(',', $invoice_m['items']); foreach($items_mass as $item_key => $item_value) { $item_split = explode('-', $item_value); echo '<pre>' . print_r($item_split, true) . '</pre>'; foreach($item_split as $item_key_final => $item_value_final) { $invoice .= ' <tr class="item-row"> <td class="item-name"><div class="delete-wpr">' . $item_value_final[1] . '</div></td> <td class="description">THIS IS THE DESCRIPTION</td> <td><span class="cost">$650.00</span></td> <td><span class="qty">1</span></td> <td><span class="price">$650.00</span></td> </tr>'; } } } return $invoice; } else { return false; } } else { return false; } } } ?> This is what is displayed. Array ( => 1 [1] => Test Product [2] => 6.99 [3] => 2 ) Array ( => 5 [1] => Tester Product [2] => 600.99 [3] => 1 ) THIS IS THE DESCRIPTION $650.00 1 $650.00 e THIS IS THE DESCRIPTION $650.00 1 $650.00 . THIS IS THE DESCRIPTION $650.00 1 $650.00 THIS IS THE DESCRIPTION $650.00 1 $650.00 THIS IS THE DESCRIPTION $650.00 1 $650.00 e THIS IS THE DESCRIPTION $650.00 1 $650.00 0 THIS IS THE DESCRIPTION $650.00 1 $650.00 THIS IS THE DESCRIPTION $650.00 1 $650.00 I need it so that I can use each of the array's above and echo out each item (key) individually. I don't understand whats going wrong? Many thanks, James. |