PHP - Game Taking Far Too Long To Update Database
Hi All,
Long question but I hope someone will be able to point me in the right direction. At the moment I am writing a cricket management game and and each hour each team is updated with the code Code: [Select] <?php #Players MUST be updated from this screen so they cna get team bonuses $teamUpdateTime=$team['teamUpdateTime']; #This is the time that the team is updated $teamMorale=$team['morale']; #Get the teams morale while($teamUpdateTime<$updateTime) { #Keep looping through this until we are up to date echo "<BR>".$team['name']; #Work out changes to team morale if($teamMorale>1000) $teamMorale -= mt_rand(0, 3); #If team morale is high then lower it if($teamMorale<1000) $teamMorale += mt_rand(0, 5); #If team morale is low then increase it $moraleBonus=0; #Reset the variable $confidenceBonus=0; #Reset the variable $injuryBonus=0; #Reset the variable $energyBonus=0; #Reset the variable $teamUpdateTime += 3600; #Add an hour to the time include("hourly_update_player.php"); #Do players now } #Save the team $sqlTeam = "UPDATE teams SET morale='$teamMorale', teamUpdateTime='$teamUpdateTime' WHERE teamID='{$team['teamID']}'"; if(!mysql_query($sqlTeam, $sqldb)) die('Error: ' . mysql_error()); //Update the record, if there is an error then show it ?> the line include("hourly_update_player.php"); #Do players now then activates the following code Code: [Select] <?php #Playeres will have to be updated with the team because we have to check for team medic $players = mysql_query("SELECT playerID, name, injuryTime, energy, morale, confidence, fitness FROM players WHERE teamPlayedFor='$team[teamID]'"); #Get all the players of the team while($player = mysql_fetch_array($players)) { #Go through all the players of the team echo "<BR>".$player['name']; # Do all the updating of player stats here. I won't put the full code here as it is not needed for the question on phpfreaks. $sqlPlayer = "UPDATE players SET energy='$energy', confidence='$confidence', morale='$morale', injuryTime='$injuryTime' WHERE playerID='{$player[playerID]}'"; #Update player if(!mysql_query($sqlPlayer,$sqldb)) die('Error: ' . mysql_error()); //Update the record, if there is an error then show it } ?> Each team has around 25 players to update. With ten teams (250 players all up) in the game (the game is still pre-alpha) to test it all this takes 8 seconds to go through all the teams and their players. Unfortunately in this 8 seconds nobody else can use the database as it locks it up. I tried to have the players update by itself (so it only has to go through the players database once) but cannot work out how to have team affects on the player - for example if the team has a specialist batting coach then the player gets an extra batting point each hour so it needs to go through the teams first. MY QUESTIONS A) How can I speed this up? When the game goes into the public domain I would like to see around 1-5 thousand teams, this could take up to 800-4,000 seconds - waaaay to long. B) When it is updating the database I can't play the game, it simply says loading until the updates are finished and then continues as normal; with thousands of teams I do expect a bit of delay but how can I keep parts of the database open that aren't being used? C) Each time I go through a team the players database is reloaded, can JOINS fix this? Or is there another way of doing this? Similar TutorialsThe SOAP request initialization is taking too long to execute. We have analyzed the system and application logs which suggest that the issue resides with SOAP request initialization. We are using PHP5.3 to call .net web service using SOAP. Please suggest. I have several registration systems that were designed some time ago running mysql. How long do I have until I have to competely move to mysqli? I am working on recoding them, but it is taking some time. Does anyone know when it will become an issue?
Code: [Select] require('../conn/db_connection.php'); //seleksi restoran $pilih_resto="select * from restoran"; $query_pilih_resto=mysql_query($pilih_resto); echo "<h3>Truly Data : </h3>"; while($resto=mysql_fetch_array($query_pilih_resto)){ echo"<font color='red'>".$resto["id_restoran"].".". $resto["nama_restoran"]."</font><br>"; $seleksi_menu_1="select * from jenis_menu"; $query_menu_1=mysql_query($seleksi_menu_1); while($menu_1=mysql_fetch_array($query_menu_1)){ echo "<font color='green'>".$menu_1["id_jenis_menu"]."</font><br>"; $seleksi_data_eat="select * from eat where id_restoran like '".$resto["id_restoran"]."' and id_jenis_menu like '".$menu_1["id_jenis_menu"]."'"; $query_eat=mysql_query($seleksi_data_eat); while($eat=mysql_fetch_array($query_eat)){ echo $eat["nama_eat"]."<br>"; } } echo"<br>"; } echo "------------------------------<br>"; echo "<h3>Random Data : </h3>"; $pilih_resto_2="select * from restoran"; $query_pilih_resto_2=mysql_query($pilih_resto_2); $menu_PNP="PNP"; $menu_PBK="PBK"; $menu_UTM_1="UTM"; while($data_resto=mysql_fetch_array($query_pilih_resto_2)){ echo "<b>".$data_resto["id_restoran"]."-".$data_resto["nama_restoran"]."</b><br>"; $seleksi_data_eat_PNP="select * from eat where id_restoran like '".$data_resto["id_restoran"]."' and id_jenis_menu like '".$menu_PNP."'"; $seleksi_data_eat_PBK="select * from eat where id_restoran like '".$data_resto["id_restoran"]."' and id_jenis_menu like '".$menu_PBK."'"; $seleksi_data_eat_UTM="select * from eat where id_restoran like '".$data_resto["id_restoran"]."' and id_jenis_menu like '".$menu_UTM_1."'"; $query_eat_UTM=mysql_query($seleksi_data_eat_UTM); $jml_data_UTM=mysql_num_rows($query_eat_UTM); echo "Summary of main Menu : $jml_data_UTM<br>"; $query_eat_PNP=mysql_query($seleksi_data_eat_PNP); $query_eat_PBK=mysql_query($seleksi_data_eat_PBK); while($eat_PNP=mysql_fetch_array($query_eat_PNP)){ $data_eat_PNP[]=$eat_PNP["nama_eat"]; } while(list($index_PNP,$data_PNP)=each($data_eat_PNP)){ $data_eat_PNP_list[$index_PNP]=$data_PNP; } while($eat_PBK=mysql_fetch_array($query_eat_PBK)){ $data_eat_PBK[]=$eat_PBK["nama_eat"]; } while(list($index_PBK,$data_PBK)=each($data_eat_PBK)){ $data_eat_PBK_list[$index_PBK]=$data_PBK; } while($eat_UTM=mysql_fetch_array($query_eat_UTM)){ $eat_UTMx[]=$eat_UTM["nama_eat"]; } for($i=0;$i<$jml_data_UTM;$i++){ $random_data_PNP[$i]=array_rand($data_eat_PNP_list,1); $random_data_PBK[$i]=array_rand($data_eat_PBK_list,1); echo "<font color='red'>".$data_eat_PNP_list[$random_data_PNP[$i]]."</font>---<font color='green'>". $eat_UTMx[$i]."</font>---<font color='blue'>".$data_eat_PBK_list[$random_data_PBK[$i]]."</font><br>"; } } Please Help, There is a random error data how to create random data like this? Data => Restoran A: Menu appetizers : - Sup - Sate Usus - Trancam Main Menu - Nasi Goreng - Nasi Goreng Putih - Nasi + Ayam Penyet - Nasi + Bebek Panggang - Ikan Gurame Asam + Nasi - Nasi Soto Menu Dessert - Pudding - Buah Segar - Juice Aplukat Restoran B : Menu appetizers -Sup Ikan Paprika -Sup Jamur Spesial -Sup Urat Sapi Saus Tiram -Sup May Jala - Jala Main Menu - Bubur Ayam Kombinasi - Bubur Ayam/Sapi Clay Pot - Bubur Telor Pitan Clay Pot - Gurame Panggang - Pangsit Udang - Cumi-cumi Goreng Special - Kepiting Lembek Mentega - Sayap Ayam Panggang Dessert -Juice Alpukat -Mix Juice -Sui Kiau Goreng Salad -Ha Kaou Sayuran Out Put : Restoran A : Menu e ---+--- Main Menu --+---- Dessert ---------------------------------------------------- Sup ------- Nasi Goreng ------- Pudding Sup ------- Nasi Goreng Putih ------- Juice Aplukat Sate Usus ------- Nasi + Ayam Penyet ------- Pudding Sup ------- Nasi + Bebek Panggang ------- Buah Segar Trancam ------- Ikan Gurame Asam + Nasi ------- Buah Segar Sate Usus ------- Nasi Soto ------- Pudding Restoran B : Menu Pembuka ---+-- Menu Utama --+--- Menu Penutup ----------------------------------------------------------------------- Sup Ikan Paprika ------- Bubur Ayam Kombinasi ------- Juice Alpukat Sup Urat Sapi Saus Tiram ------- Bubur Ayam/Sapi Clay Pot ------- Sui Kiau Goreng Salad Sup May Jala-Jala ------- Bubur Telor Pitan Clay Pot ------- Juice Alpukat Kepiting Lembek Mentega ------- Gurame Panggang ------- Juice Alpukat Sup Urat Sapi Saus Tiram ------- Pangsit Udang ------- Mix Juice Sup May Jala-Jala ------- Cumi-cumi Goreng Special ------- Ha Kaou Sayuran Sup Jamur Spesial ------- Kepiting Lembek Mentega ------- Sui Kiau Goreng Salad Sup May Jala-Jala ------- Sayap Ayam Panggang ------- Ha Kaou Sayuran Note : appetizers and desserts at random based on count of data main menu This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=321088.0 Hi i have this simple update form and scrip but somehow it doesnt seem to be update the field on the database can someone help out please. The html form is the second form bellow where the action send to status_update.php HTML FORM Code: [Select] <?php include("../header.html"); ?> <?php include("header_news.html"); extract($_REQUEST,EXTR_SKIP); ?><?php /* print("sfilm_refnum = $sfilm_refnum<BR>"); print("sfilm_addr01 = $sfilm_addr01<BR>"); print("sfilm_postcode = $sfilm_postcode<BR>"); print("Film Client = $fclient<BR>"); */ ?> <form id="search" action="list.php" method="post" name="search"> <table width="780" border="0" cellspacing="0" cellpadding="4" bgcolor="#eeeeee"> <tr> <td align="right" width="140"></td> <td width="320"><span class="hofblack10"> </span> </td> <td align="center" width="100"><input type="hidden" name="lstart" value="<?php print("$lstart"); ?>" /><input type="hidden" name="lend" value="<?php print("$lend"); ?>" /><input type="hidden" name="lamount" value="<?php print("$lamount"); ?>" /></td> <td align="center" width="100"></td> <td align="right"></td> </tr> </table> </form> <table width="780" border="0" cellspacing="0" cellpadding="4" bgcolor="#4050c4"> <tr> <td width="60" class="hofwhite10">action</td> <td width="140"><span class="hofwhite14">DATE</span></td> <td width="80"><span class="hofwhite14">ID</span></td> <td><span class="hofwhite14">News Titile</span></td> <td width="100"><span class="hofwhite14">Status</span></td> </tr> <tr height="0"> <td bgcolor="white" width="60"></td> <td bgcolor="white" width="140" height="0"></td> <td bgcolor="white" width="80" height="0"></td> <td bgcolor="white" height="0"></td> <td bgcolor="white" width="100" height="0"></td> </tr> </table><table width="780" border="0" cellspacing="0" cellpadding="4"><tr> <td width="60"></td> <td width="80"></td> <td><a class="blueullrg" href="add.php">Add News</a></td> <td align="right" width="120"></td> </tr> <tr height="0"> <td width="60" height="0"></td> <td width="80" height="0"></td> <td height="0"></td> <td align="right" width="120" height="0"></td> </tr> </table> <?php //get the DB connection variables include("../../../includes/config.php"); //connect to DB $connection = @mysql_connect($db_address,$db_username,$db_password) or die("Couldn't CONNECT."); $db = @mysql_select_db($db_name, $connection) or die("Couldn't select DATABASE."); $query2="SELECT * FROM news WHERE !(news_status='deleted')"; $result2 = mysql_query($query2) or die("Couldn't execute QUERY - Select NEWS Qty"); $fqty = mysql_num_rows($result2); //SELECT or FIND the same USERNAME $query3="SELECT * FROM news WHERE !(news_status='deleted') ORDER BY news_id DESC"; $result3 = mysql_query($query3) or die("Couldn't execute QUERY - Select NEWS"); while ($row = mysql_fetch_array($result3)) { $news_id = $row['news_id']; $news_title = $row['news_title']; $news_story = $row['news_story']; $news_image = $row['news_image']; $news_image_caption = $row['news_image_caption']; $news_image_link = $row['news_image_link']; $news_date_day = $row['news_date_day']; $news_date_month = $row['news_date_month']; $news_date_year = $row['news_date_year']; $news_status = $row['news_status']; $news_website = $row['news_website']; $news_date_created = $row['news_date_created']; $news_date_modified = $row['news_date_modified']; ?> <table width="780" border="0" cellspacing="0" cellpadding="4" bgcolor="#eeeeee"> <tr> <td width="60"><span class="hofblack10"> <?php if($news_status=="deleted"){ print("<a class='hifblack10'>deleted</span>"); }ELSE{ print("<a class='blueul' href='edit.php?id=$news_id'>edit</a>"); } ?> </span></td> <td width="140"><span class="titlegrey12"> <?php if(!$news_date_day) { echo "00"; } else{ echo $news_date_day; } echo "/"; if(!$news_date_month) { echo "00"; }else{ echo $news_date_month; } echo "/"; if(!$news_date_year) { echo "0000"; }else{ echo $news_date_year; } ?> </span></td> <td width="80"><span class="titlegrey12"><?php print("$news_id"); ?></span> </td> <td><?php if($news_status=="deleted") { print("<class='hofblack10'>$news_title</span>"); }ELSE{ print("<a class='blueul' href='edit.php?id=$news_id'>$news_title</a>"); } ?></td> <td width="100"> <form id="list_update" action="status_update.php" method="post" name="list_update"> <select name="newnstatus" size="1"> <option <?php if($row['news_status'] == "") { print("selected"); } ?> selected="selected" value="">Status...</option> <option <?php if($row['news_status'] == "on") { print("selected"); } ?> value="on">On</option> <option <?php if($row['news_status'] == "off") { print("selected"); } ?> value="off">Off</option> <option <?php if($row['news_status'] == "deleted") { print("selected"); } ?> value="deleted">Delete</option> </select> <input type="hidden" name="nstatus" value="<?php echo $row[news_status]; ?>" /> <input type="hidden" name="id" value="<?php echo $row[news_id]; ?>" /> <input type="submit" name="update" value="update" /> </form> </td> </tr> <tr height="0"> <td bgcolor="white" width="60"></td> <td bgcolor="white" width="140" height="0"></td> <td bgcolor="white" width="80" height="0"></td> <td bgcolor="white" height="0"></td> <td bgcolor="white" width="100" height="0"></td> </tr> </table> <?php } mysql_close($connection);//}?> <table width="780" border="0" cellspacing="0" cellpadding="4"> <tr> <td width="60"></td> <td width="80"></td> <td><a class="blueullrg" href="add.php">Add News</a></td> <td align="right" width="120"></td> </tr> </table><?php // include("list_navigation.html"); ?> <?php include("../footer.html"); ?> </div></body></html> The action script php Code: [Select] <?php /* echo "fstatus: ".$fstatus."<BR>"; echo "id: ".$id."<BR>"; echo "fclient: ".$fclient."<BR>"; echo "newfstatus: ".$newfstatus."<BR>";*/ //set the date of agreement $timestamp = date('l jS \of F Y h:i:s A'); //get the DB connection variables include("../../../includes/config.php"); //connect to DB $connection = @mysql_connect($db_address,$db_username,$db_password) or die("Couldn't CONNECT."); $db = @mysql_select_db($db_name, $connection) or die("Couldn't select FILMS DATABASE."); // All appears well, so enter into database $query= "UPDATE news SET news_status = '$newnstatus' WHERE news_id='$id'"; $result = mysql_query($query) or die("could not execute query - Update FILMS Record to DB"); //setup an email to the Admin @ hof, w/o attachment $emailto="xx@xxx.co.uk"; $emailfrom="no-reply@xxxx.co.uk"; $emailsubject="xx Record Updated"; $emailmessage="Hello Registrar\n\n"; $emailmessage.="News ID: ".$id."\n"; $emailmessage.="Updated on: ".$timestamp."\n\n"; $emailmessage.="Status was: ".$nstatus."\n"; $emailmessage.="Status now: ".$newfnstatus."\n"; $emailmessage.="Thank you,\n\n"; $emailmessage.="Web Site ROBOT\n"; $emailmessage.="(Administrator)\n"; $emailmessage.="xxx.co.uk | xxx.biz\n"; $emailmessage.="----------------------------------------------\n"; $emailmessage.="e. http://www.xxx.co.uk/contact.php\n"; $emailmessage.="w. http://www.xxx.co.uk\n"; $emailheader="From: xxx.co.uk<$emailfrom>"; $emailheader .= 'Cc: xxx@xxx.co.uk'."\r\n"; $emailheader .= 'Bcc: xxx@xxxxx.co.uk'."\r\n"; $ok=mail($emailto,$emailsubject,$emailmessage,$emailheader); mysql_close($connection); if ($ok) { header("Location: list.php"); /* Redirect browser */ exit; } else { $errmsg="There was a problem, please try later or telephone us direct."; $errsta="1"; include("edit_error.html"); //echo "<p>Mail could not be sent. Sorry!</p>"; exit; } ?> Thanks in advance I need a map which locates all the stores addresses(Less than 10). Those address must be retreived from the database. But the database don't contain any lat or long field. Therefore geocoding an address into their corresponding lat and long coordinates must be done and appropriate markers must be placed.
The code which I have at the moment is as follows:-
<?php require_once '../model/stores.php'; $obj=new Stores(); $result=$obj->getStores(); $new_array = array(); while($row=mysql_fetch_assoc($result)){ $new_array[] = $row['stores_address']; } $add_js = json_encode( $new_array ); ?> <html> <head> <style> #map_canvas { width: 500px; height: 500px; } </style> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script> <script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script> <script> $(document).ready(function () { var map; var elevator; var myOptions = { zoom: 1, center: new google.maps.LatLng(0, 0), mapTypeId: 'terrain' }; map = new google.maps.Map($('#map_canvas')[0], myOptions); //var addresses = ['Norway', 'Africa', 'Asia','North America','South America']; var addresses = <?php echo $add_js ?>;; for (var x = 0; x < addresses.length; x++) { $.getJSON('http://maps.googleapis.com/maps/api/geocode/json? address=' +addresses[x]+'&sensor=false', null, function (data) { var p = data.results[0].geometry.location var latlng = new google.maps.LatLng(p.lat, p.lng); new google.maps.Marker({ position: latlng, map: map }); }); } }); </script> </head> <body> <div id="map_canvas"></div> </body> </html>I have looked on various forums and other web resources but no use as none of them worked out for me...Hope any genius would help me to solve the problem. Edited by Naseem, 15 August 2014 - 12:25 AM. Hello. I just inherited a game stats system but it's not working properly. I'm gonna post the entire script: <?php error_reporting(E_ERROR | E_WARNING | E_PARSE); $servername = "127.0.0.1"; $username = ""; $password = ""; $dbname = ""; $addresses = Array(); $nicknames = Array(); $servers = Array(); $times = Array(); $find_ip = $_GET["ip"]; $find_name = $_GET["nick"]; if(isset($_GET["format"])) { $format = $_GET["format"]; } else { $format = "include"; } $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { ReturnError("NO_CONNECTION"); } function ReturnError($error) { global $format; if($format == "mod") die("!DATA!ERROR:" .$error. "!DATA!"); else die("ERROR:" . $error); } function ReturnData($data) { global $format; if($format == "mod") die("!DATA!SUCCESS:" .$data. "!DATA!"); else die("SUCCESS:" .$data); } function GetServerIP() { if (!empty($_SERVER['HTTP_CLIENT_IP'])) return $_SERVER['HTTP_CLIENT_IP']; else if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) return $_SERVER['HTTP_X_FORWARDED_FOR']; else return $_SERVER['REMOTE_ADDR']; } function GetTimestamp() { $now = DateTime::createFromFormat('U.u', number_format(microtime(true), 6, '.', '')); $now->format("m-d-Y H:i:s.u"); $local = $now->setTimeZone(new DateTimeZone('Europe/Prague')); return $local->getTimestamp(); } function GetFormatedTime() { $now = DateTime::createFromFormat('U.u', number_format(microtime(true), 6, '.', '')); $now->format("m-d-Y H:i:s.u"); $local = $now->setTimeZone(new DateTimeZone('Europe/Prague')); return $local->format("Y-m-d H:i:s.u"); } function AddAddress($addr) { global $addresses; if(in_array($addr, $addresses, true)) { return false; } else { array_push($addresses, $addr); return true; } } function AddTime($time) { global $times; if(in_array($time, $times, true)) { return false; } else { array_push($times, $time); return true; } } function AddNickname($nick) { global $nicknames; if(in_array($nick, $nicknames, true)) { return false; } else { array_push($nicknames, $nick, true); return true; } } function AddServer($server) { global $servers; if(in_array($server, $servers, true)) { return false; } else { array_push($servers, $server, true); return true; } } function LookForIPs($ip) { global $conn; $sql = "SELECT * FROM `connections` WHERE `IP` = '".$ip."'"; $result = $conn->query($sql); if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { AddAddress($row["IP"]); AddServer($row["serverIP"]); AddTime(Array($row["datestamp"], $row["datestring"], $row["serverIP"])); if(AddNickname($row["nickname"]) && $row["nickname"] != "Player" && $row["nickname"] != "A_Edition_V2") { LookForNicknames($row["nickname"]); } } return true; } else { return false; } } function LookForNicknames($nick) { global $conn; $sql = "SELECT * FROM `connections` WHERE `nickname` LIKE '".$nick."'"; $result = $conn->query($sql); if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { AddNickname($row["nickname"]); AddServer($row["serverIP"]); AddTime(Array($row["datestamp"], $row["datestring"], $row["serverIP"])); if(AddAddress($row["IP"])) { LookForIPs($row["IP"]); } } return true; } else { return false; } } function SortTimes() { global $times; $good = false; while($good == false) { $good = true; for($i = 0; $i < count($times); $i++) { if($i+1 == count($times)) continue; if($times[$i][0] < $times[$i + 1][0]) { $tmp = $times[$i]; $times[$i] = $times[$i + 1]; $times[$i+1] = $tmp; $good = false; } } } } function GenerateLastSeenString($fromTime) { $time_now = GetTimestamp(); if($time_now < $fromTime) { return "N/A"; } if($fromTime == 0 || $fromTime =="") { return "N/A"; } $ss = $time_now - $fromTime; $seconds = $ss%60; $minutes = floor(($ss%3600)/60); $hours = floor(($ss%86400)/3600); $days = floor(($ss%2592000)/86400); $months = floor($ss/2592000); $str = ""; if($months != 0) { if($str != "") $str = $str . " "; if($days == 1) $str = $str . $months . " month"; else $str = $str . $months . " months"; } if($days != 0) { if($str != "") $str = $str . " "; if($days == 1) $str = $str . $days . " day"; else $str = $str . $days . " days"; } if($hours != 0) { if($str != "") $str = $str . " "; if($hours == 1) $str = $str . $hours . " hour"; else $str = $str . $hours . " hours"; } if($minutes != 0) { if($str != "") $str = $str . " "; if($minutes == 1) $str = $str . $minutes . " minute"; else $str = $str . $minutes . " minutes"; } if($seconds != 0) { if($str != "") $str = $str . " "; if($seconds == 1) $str = $str . $seconds . " second"; else $str = $str . $seconds . " seconds"; } return $str. " ago"; } function ClearResult($arr) { for($i = 0; $i < count($arr); $i++) { if(gettype($arr[$i]) == "boolean") { //echo "Found bool at $i"; array_splice($arr, $i, 1); } } return $arr; } function PrintArray($arr) { for($i = 0; $i < count($arr); $i++) { echo $arr[$i]; if($i + 1 != count($arr)) { echo ", "; } } } if($format == "mod") { LookForNicknames($find_name); LookForIPs($find_ip); $nicknames = ClearResult($nicknames); $addresses = ClearResult($addresses); $servers = ClearResult($servers); $conn->close(); /*if (!filter_var($find_ip, FILTER_VALIDATE_EMAIL) && $find_ip != "") { $find_ip = $addresses[0]; }*/ if($find_ip == "") { $find_ip = $addresses[0]; } if($find_ip == "") { $find_ip = "0.0.0.0"; } if(count($nicknames) == 0 && count($addresses) == 0) { ReturnError("NOT_FOUND"); } echo "!DATA!"; echo "Nicknames used: "; PrintArray($nicknames); echo "*-*"; echo "Total IPs used: "; echo count($addresses); echo "*-*"; echo "Location: "; echo file_get_contents("http://127.0.0.1/db/getlocation.php?ip=$find_ip"); echo "*-*"; echo "Connected: "; echo count($times); echo " times*-*"; SortTimes(); if(GetTimestamp() - $times[0][0] < 60 * 60) echo "Last seen: " . GenerateLastSeenString($times[1][0]) . "*-*"; else echo "Last seen: " . GenerateLastSeenString($times[0][0]) . "*-*"; echo "First seen: " . GenerateLastSeenString($times[count($times)-1][0]); echo "!DATA!"; } else if($format == "debug") { LookForNicknames($find_name); LookForIPs($find_ip); $nicknames = ClearResult($nicknames); $addresses = ClearResult($addresses); $servers = ClearResult($servers); $conn->close(); /*if (!filter_var($find_ip, FILTER_VALIDATE_EMAIL) && $find_ip != "") { $find_ip = $addresses[0]; }*/ if($find_ip == "") { $find_ip = $addresses[0]; } if($find_ip == "") { $find_ip = "0.0.0.0"; } if(count($nicknames) == 0 && count($addresses) == 0) { ReturnError("NOT_FOUND"); } echo "Nicknames used: "; PrintArray($nicknames); echo "<br>"; echo "IPs used: "; PrintArray($addresses); echo "<br>"; echo "Location: "; echo file_get_contents("http://127.0.0.1/db/getlocation.php?ip=$find_ip"); echo "<br>"; echo "Connected: "; echo count($times); echo " times<br>"; SortTimes(); echo "Last seen: " . GenerateLastSeenString($times[0][0]) . "<br>"; echo "First seen: " . GenerateLastSeenString($times[count($times)-1][0]) . "<br>"; echo $find_name; } ?> The problem is that for some nicknames it returns a proper output which should look like this:
But sometimes it just returns lots and lots of data even if the nickname I ask for is unique enough:
Here's how the database looks:
I don't know what's wrong with the script because I'm a PHP beginner. If someone could take a look at it and tell me what's the issue I'd appreciate. Edited September 22, 2020 by jevgienijHello, 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. Hello, I have a form where individuals can update there personal information that is already stored in a database, i.e name, address, phone number etc. There are several fields they can update. Right now it sends an email to the owner that an individual has updated their records, and sends all the fields that are in the table. Is it possible to let the owner be notified by email which individual field was updated? Example their phone number has changed they make the update and the owner gets an e-mail with just that field update. I hope I explained myself properly. Thank you in advance. I'm not shore what to do this update code isn't updating my database this is just the update code for my login Code: [Select] mysql_query("UPDATE users SET session_id='$session' WHERE email='$email' AND password='$pas'") or die(mysql_error()); //Add session ID to DB mysql_query("UPDATE users SET login_ip='$ip' WHERE email='$email' AND password='$pas'") or die(mysql_error()); //Add login IP to DBand this is all of it Code: [Select] <title>Log In</title><?php require('database.php'); //Include DB connection information if (isset($_POST['login'])) { //Execute the following if form is submitted $ip = mysql_real_escape_string($_SERVER["REMOTE_ADDR"]); //Geet user's IP Address $email = mysql_real_escape_string($_POST['email']); //Post email from form $password = mysql_real_escape_string(sha1(md5($_POST['pass']))); //Post password from form and encrypt if (empty($email) || empty($password)) { //Check for empty fields die("<b>Error:</b> All fields are required to be filled in."); } $check = mysql_query("SELECT * FROM users WHERE email = '$email'") or die(mysql_error()); $check2 = mysql_num_rows($check); if ($check2 == 0) { //Check if account exists die("<b>Error:</b> Email and password do not match the database."); } $row = mysql_fetch_array($check); $db_password = $row['password']+$row['key']; if ($password != $db_password) { //Check if password is correct die("<b>Error:</b> Email and password do not match the database."); } $allowed = $row['u']; if ($allowed != 1) { //Check if they have permission die("<b>Error:</b> You do not have permission to view this section."); } function randomstring($length = 10) { $validCharacters = "abcdefghijklmnopqrstuxyvwz1234567890"; $validCharNumber = strlen($validCharacters); $result = ""; for ($i = 0; $i < $length; $i++) { $index = mt_rand(0, $validCharNumber - 1); $result .= $validCharacters[$index]; } return $result; } $session = randomstring(); $key = $row['key']; $pas = $password . $key; mysql_query("UPDATE users SET session_id='$session' WHERE email='$email' AND password='$pas'") or die(mysql_error()); //Add session ID to DB mysql_query("UPDATE users SET login_ip='$ip' WHERE email='$email' AND password='$pas'") or die(mysql_error()); //Add login IP to DB $level = $row['accounttype']; $u = $row['u']; $fs = $row['fs']; $bc = $row['bc']; $fam = $row['fam']; $future = time() + 1209600; setcookie("uemail", $email, $future); //Set cookie containing username setcookie("sessionid", $session, $future); //Set cookie containging session ID setcookie("acounttype", $level, $future); setcookie("u", $u, $future); setcookie("fs", $fs, $future); setcookie("bc", $bc, $future); setcookie("fam", $fam, $future); ////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////// //header("Location: undefined.php"); //Redirect to members page } else { //If form is not submitted display the form echo<<<login <center> <h1>Log In To The Undefiend Section</h1> <h2>Or GO <a href="../main.php">Home</a></h2> <form method="post" action=""> Email: <input type="text" name="email"><br> Password: <input type="password" name="pass"><br> <input type="submit" name="login" value="Login"><br><br> </form></center> login; } ?> Hello, I am trying to update my database using a form. While submitting this function is called, but nothing is changed. If I replace the variables with values, the function works fine, but not with variables. Code: [Select] function updateCandidate($id, $F_Name, $L_Name, $Gender, $Bday, $PhoneNo, $Address, $City, $Country, $Nationality, $experience, $Stat) { $q = "UPDATE candidates SET F_Name = '$F_Name', L_Name='$L_Name', Gender='$Gender', Bday='$Bday', PhoneNo='$PhoneNo', Address = '$Address', City='$City', Country = '$Country', Nationality = '$Nationality', Experience_idExperience='$experience', Status= $Stat WHERE Users_UsersID = $id"; return mysql_query($q, $this->connection); I am trying to make a rating system and this script is not working. Code: [Select] $ratingget = $_REQUEST['star2']; mysql_select_db($database_news, $news); $query_ratingsys = "UPDATE news SET votes = votes +1 AND rating = rating +'$ratingget' WHERE id = '$id'"; $ratingsys = mysql_query($query_ratingsys, $news) or die(mysql_error()); I'm trying to update my database so that if someone enters an e-mail address that doesn't exist, the program updates the database with the new address. I've tested everything and $result returns the correct data every time (0 or 1) but if the address doesn't exist, nothing gets updated. I know I'm missing something, just not sure what it is... Code: [Select] { $result = mysql_query(" SELECT * FROM PlayerInfo WHERE Player_Email = '$playeremail'"); IF($result) { IF (mysql_num_rows($result) = 0) { //Insert into database: new e-mail address... } } I've also tested the insert into statement and it works, so that's not the issure. Any help appreciated. Thanks. Hi guys, I have had to make some changes to a database that I updated hockey players stats with. Since doing this I can no longer edit player stats in my admin section of the website. I was wondering if someone could possibly have a look at it for me. It is driving me nuts not being able to fix it. What should happen is: I choose the player from a list of teams to update. Their stats show up on next page in a table for the different competitions they play in (league, cup, play-offs). I could then update the stats and then once pressing the edit button at the bottom, this then updates my SQL database. Can anyone help? <?php if ($stat==1) { // normal players $table = "players"; } else { // snl_players $table ="snl_players"; } if ($act==edit) { $query11 = "SELECT * FROM `$table` WHERE `PlayerID` = '$PlayerID'"; $result11 = mysql_query($query11) or die ('Error: Sh2'); $rows = mysql_fetch_array($result11); $PlayerID = $rows['PlayerID']; $TeamID = $rows['TeamID']; $Team = $rows['Team']; $Player = $rows['Player']; $Games = $rows['Games']; $Goals = $rows['Goals']; $PPGoals = $rows['PPGoals']; $SHGoals = $rows['SHGoals']; $Assists = $rows['Assists']; $PIM = $rows['PIM']; $Points = $rows['Points']; $GamesCup = $rows['GamesCup']; $GoalsCup = $rows['GoalsCup']; $PPGoalsCup = $rows['PPGoalsCup']; $SHGoalsCup = $rows['SHGoalsCup']; $AssistsCup = $rows['AssistsCup']; $PIMCup = $rows['PIMCup']; $PointsCup = $rows['PointsCup']; /* $GamesNPL = $rows['GamesNPL']; $GoalsNPL = $rows['GoalsNPL']; $PPGoalsNPL = $rows['PPGoalsNPL']; $SHGoalsNPL = $rows['SHGoalsNPL']; $AssistsNPL = $rows['AssistsNPL']; $PIMNPL = $rows['PIMNPL']; $PointsNPL = $rows['PointsNPL']; */ $GamesPO = $rows['GamesPO']; $GoalsPO = $rows['GoalsPO']; $PPGoalsPO = $rows['PPGoalsPO']; $SHGoalsPO = $rows['SHGoalsPO']; $AssistsPO = $rows['AssistsPO']; $PIMPO = $rows['PIMPO']; $PointsPO = $rows['PointsPO']; $Nationality = $rows['Nationality']; $query11 = "SELECT * FROM `teams` WHERE `TeamID` = '$TeamID'"; $result11 = mysql_query($query11) or die ('Error: Sh2'); $rows = mysql_fetch_array($result11); $TeamName = $rows['TeamName']; echo ("<form name=\"form1\" method=\"post\" action=\"playerstats.php?act=editdo&PlayerID=$PlayerID&stat=$stat\"> <table width=\"80%\" border=\"0\"> <tr> <td width=\"30%\" class=\"data\">Player Name </td> <td width=\"70%\"><input name=\"Player\" type=\"text\" id=\"Player\" value=\"$Player\"></td> </tr> <tr> <td class=\"data\">Associated Team ID </td> <td class=\"data\"> <select name=\"TeamID\">"); $query11 = "SELECT * FROM `teams`"; $result11 = mysql_query($query11) or die ('Error: Sh2'); while ( $rows = mysql_fetch_array($result11) ) { $TeamName = $rows['TeamName']; $TeamID2 = $rows['TeamID']; if ($TeamID==$TeamID2) { echo(" <option value=\"$TeamID2\" selected>$TeamName</option>"); } else { echo(" <option value=\"$TeamID2\">$TeamName</option>"); } } echo("</select></td> </tr> <tr> <td class=\"data\">Games</td> <td><input name=\"Games\" type=\"text\" id=\"Games\" size=\"6\" value=\"$Games\"></td> </tr> <tr> <td class=\"data\">Goals</td> <td><input name=\"Goals\" type=\"text\" id=\"Goals\" size=\"6\" value=\"$Goals\"></td> </tr> <tr> <td class=\"data\">PPGoals</td> <td><input name=\"PPGoals\" type=\"text\" id=\"Goals\" size=\"6\" value=\"$PPGoals\"></td> </tr> <tr> <td class=\"data\">SHGoals</td> <td><input name=\"SHGoals\" type=\"text\" id=\"Goals\" size=\"6\" value=\"$SHGoals\"></td> </tr> <tr> <td class=\"data\">Assists</td> <td><input name=\"Assists\" type=\"text\" id=\"Assists\" size=\"6\" value=\"$Assists\"></td> </tr> <tr> <td class=\"data\">PIM</td> <td><input name=\"PIM\" type=\"text\" id=\"PIM\" size=\"6\" value=\"$PIM\"></td> </tr> <tr> <td class=\"data\">Points</td> <td><input name=\"Points\" type=\"text\" id=\"Points\" size=\"6\" value=\"$Points\"></td> </tr> <tr> <td class=\"data\">GamesCup</td> <td><input name=\"GamesCup\" type=\"text\" id=\"GamesCup\" size=\"6\" value=\"$GamesCup\"></td> </tr> <tr> <td class=\"data\">GoalsCup</td> <td><input name=\"GoalsCup\" type=\"text\" id=\"GoalsCup\" size=\"6\" value=\"$GoalsCup\"></td> </tr> <tr> <td class=\"data\">PPGoalsCup</td> <td><input name=\"PPGoalsCup\" type=\"text\" id=\"GoalsCup\" size=\"6\" value=\"$PPGoalsCup\"></td> </tr><tr> <td class=\"data\">SHGoalsCup</td> <td><input name=\"SHGoalsCup\" type=\"text\" id=\"GoalsCup\" size=\"6\" value=\"$SHGoalsCup\"></td> </tr> <tr> <td class=\"data\">AssistsCup</td> <td><input name=\"AssistsCup\" type=\"text\" id=\"AssistsCup\" size=\"6\" value=\"$AssistsCup\"></td> </tr> <tr> <td class=\"data\">PIMCup</td> <td><input name=\"PIMCup\" type=\"text\" id=\"PIMCup\" size=\"6\" value=\"$PIMCup\"></td> </tr> <tr> <td class=\"data\">PointsCup</td> <td><input name=\"PointsCup\" type=\"text\" id=\"PointsCup\" size=\"6\" value=\"$PointsCup\"></td> </tr> "); if ($stat==1) { } else { echo(" <tr><td class=\"data\">GamesPO</td> <td><input name=\"GamesPO\" type=\"text\" id=\"GamesPO\" size=\"6\" value=\"$GamesPO\"></td> </tr> <tr> <td class=\"data\">GoalsPO</td> <td><input name=\"GoalsPO\" type=\"text\" id=\"GoalsPO\" size=\"6\" value=\"$GoalsPO\"></td> </tr> <tr> <td class=\"data\">PPGoalsPO</td> <td><input name=\"PPGoalsPO\" type=\"text\" id=\"GoalsPO\" size=\"6\" value=\"$PPGoalsPO\"></td> </tr> <tr> <td class=\"data\">SHGoalsPO</td> <td><input name=\"SHGoalsPO\" type=\"text\" id=\"GoalsPO\" size=\"6\" value=\"$SHGoalsPO\"></td> </tr><tr> <td class=\"data\">AssistsPO</td> <td><input name=\"AssistsPO\" type=\"text\" id=\"AssistsPO\" size=\"6\" value=\"$AssistsPO\"></td> </tr><tr> <td class=\"data\">PIMPO</td> <td><input name=\"PIMPO\" type=\"text\" id=\"PIMPO\" size=\"6\" value=\"$PIMPO\"></td> </tr><tr> <td class=\"data\">PointsPO</td> <td><input name=\"PointsPO\" type=\"text\" id=\"PointsPO\" size=\"6\" value=\"$PointsPO\"></td> </tr><tr> <td class=\"data\">Nationality</td> <td><input name=\"Nationality\" type=\"text\" id=\"Nationality\" value=\"$Nationality\"></td> </tr> <td class=\"data\"> </td> <td> </td> </tr> <tr> <td class=\"data\"> </td> <td><input type=\"submit\" name=\"Submit\" value=\"Edit\"></td> </tr> </table> </form>"); } if ($stat!=0) { $query = "UPDATE `players` SET `Nationality` = '$Nationality', `GamesPO` = '$GamesPO' , `AssistsPO` = '$AssistsPO' , `GoalsPO` = '$GoalsPO' , `PPGoalsPO` = '$PPGoalsPO' , `SHGoalsPO` = '$SHGoalsPO' , `PointsPO` = '$PointsPO' , `PIMPO` = '$PIMPO' , `PIM` = '$PIM' , `PointsCup` = '$PointsCup' , `PIMCup` = '$PIMCup' , `AssistsCup` = '$AssistsCup' , `GoalsCup` = '$GoalsCup' , `PPGoalsCup` = '$PPGoalsCup' , `SHGoalsCup` = '$SHGoalsCup' , `GamesCup` = '$GamesCup' , `Points` = '$Points', `Assists` = '$Assists' , `Goals` = '$Goals' , `PPGoals` = '$PPGoals' , `SHGoals` = '$SHGoals' , `TeamID` = '$TeamID' , `Player` = '$Player' , `Games` = '$Games' WHERE `PlayerID` = '$PlayerID'"; $result = mysql_query($query) or die ("Can't Update"); echo ("The player has been updated.<br><br><a href=\"playerstats.php\"> Go back to the player List</a>"); } else { $query = "UPDATE `snl_players` SET `PIM` = '$PIM' , `GamesPO` = '$GamesPO' , `AssistsPO` = '$AssistsPO' , `GoalsPO` = '$GoalsPO' , `PPGoalsPO` = '$PPGoalsPO' , `SHGoalsPO` = '$SHGoalsPO' , `PointsPO` = '$PointsPO' , `PIMPO` = '$PIMPO' , `PointsCup` = '$PointsCup' , `PIMCup` = '$PIMCup' , `AssistsCup` = '$AssistsCup' , `GoalsCup` = '$GoalsCup' , `PPGoalsCup` = '$PPGoalsCup' , `SHGoalsCup` = '$SHGoalsCup' , `GamesCup` = '$GamesCup' , `Points` = '$Points', `Assists` = '$Assists' , `Goals` = '$Goals' , `PPGoals` = '$PPGoals' , `SHGoals` = '$SHGoals' , `TeamID` = '$TeamID' , `Player` = '$Player' , `Games` = '$Games' WHERE `PlayerID` = '$PlayerID'"; $result = mysql_query($query) or die ("Can't Update"); echo ("The player has been updated.<br><br><a href=\"playerstats.php\"> Go back to the player List</a>"); } } elseif ($act==teamlist) { $query112 = "SELECT * FROM `teams` WHERE `TeamID` = '$TeamID'"; $result112 = mysql_query($query112) or die ('Error: Sh2'); $rows2 = mysql_fetch_array($result112); $TeamName = $rows2['TeamName']; $Logo = $rows2['Logo']; if ($Logo!="") { echo("<img src=\"../Images/$Logo\" /><br><br>"); } else { } echo ("<strong>Edit $TeamName Players</strong><br><br>Click Player Names to edit details<br><br>"); $query11 = "SELECT * FROM `players` WHERE `TeamID` = '$TeamID'"; $result11 = mysql_query($query11) or die ('Error: Sh2'); while ( $rows = mysql_fetch_array($result11) ) { $Player = $rows['Player']; $PlayerID = $rows['PlayerID']; $TeamID = $rows['TeamID']; echo ("<span class=\"style1\"><a href=\"playerstats.php?act=edit&PlayerID=$PlayerID&stat=1\">$Player</a><br>"); } } else { echo ("Click Team Names to view players<br><br>"); $query11 = "SELECT distinct TeamID FROM `players` ORDER BY `TeamID`"; $result11 = mysql_query($query11) or die ('Error: Sh2'); while ( $rows = mysql_fetch_array($result11) ) { $TeamID = $rows['TeamID']; $query112 = "SELECT * FROM `teams` WHERE `TeamID` = '$TeamID'"; $result112 = mysql_query($query112) or die ('Error: Sh2'); $rows2 = mysql_fetch_array($result112); $TeamName = $rows2['TeamName']; echo ("<span class=\"style1\"><a href=\"playerstats.php?act=teamlist&TeamID=$TeamID&stat=1\">$TeamName</a><br>"); } echo ("<a name=\"snl\"></a><br><strong><a href=\"snlplayerstats.php\">SNL Teams</a></strong><br><br>"); } ?> Hello I am updating a SQL database - basically adding to an account field as follows... $sql1 = "select * from member where username = \"$owner\" limit 1 "; $result1 = mysql_query($sql1, $conn) or die(mysql_error()); $row1 = mysql_fetch_assoc($result1); $total_commissions = $row1['total_commissions']; $total_commissions = $total_commissions + $_SESSION['cost_per_token']; //add to data $balance = $row1['balance']; $balance = $balance + $_SESSION['cost_per_token']; //add to data #-------------------------------------------------------------------------- #Update db $sql1 = " UPDATE member SET total_commissions = \"$total_commissions\", balance = \"$balance\" WHERE username=\"$owner\" "; $result1 = mysql_query($sql1, $conn) or die(mysql_error()); is there a way to add to the data from the UPDATE query? e.g; $sql1 = " UPDATE member SET total_commissions = \"$total_commissions\ + $_SESSION['cost_per_token'] ", balance = \"$balance\ + $_SESSION['cost_per_token']" WHERE username=\"$owner\" "; I use mysql and this code that I will show says that the info was sucessfully updated, but it wasnt. please help. By the way, I am designing a website for a boy scout troop that has asked me to help. any help appreciated: Code: [Select] <?php session_start(); // Must start session first thing /* Created By Adam Khoury @ [URL=http://'http://www.flashbuilding.com/']www.flashbuilding.com[/URL] -----------------------June 20, 2008----------------------- */ // Here we run a login check if (!isset($_SESSION['id'])) { echo 'Please <a href="login.php">log in</a> to access your account'; exit(); } //Connect to the database through our include include_once "connect_to_mysql.php"; // Place Session variable 'id' into local variable $id = $_SESSION['id']; // Query member data from the database and ready it for display $sql = mysql_query("SELECT * FROM members WHERE id='$id' LIMIT 1"); while($row = mysql_fetch_array($sql)){ $rank = $row['rank']; } // Process the form if it is submitted if ($_POST['rank']) { $rank = $_POST['rank']; $sql = mysql_query("UPDATE members SET rank='$rank' where id='$id'"); echo 'Your account info has been updated, visitors to your profile will now see the new info.<br /><br /> <meta HTTP-EQUIV="REFRESH" content="3; url=http://final.net46.net/myprofile.php">'; exit(); } // close if post ?> <!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>Untitled Document</title> </head> <body> <form id="form1" name="form1" method="post" action="scout.php" onsubmit="return validate_form ( );"> <label for="rank"></label> <select name="rank" id="rank"> <option value="Scout">Scout</option> <option value="Tenderfoot">Tenderfoot</option> <option value="Second Class Scout">Second Class Scout</option> <option value="First Class Scout">First Class Scout</option> <option value="Star Scout">Star Scout</option> <option value="Life Scout">Life Scout</option> <option value="Eagle Scout">Eagle Scout</option> <option value="<?php echo $rank; ?>" selected="selected"></option> </select> <input type="submit" name="submit" id="submit" value="Save" /> </form> </body> </html> Firstly I'm completely new to this game so bare with me please! I've installed easy php and using phpMyAdmin I have setup a database for a list of employees in an office, I have managed to get some help to return this information to a webpage using some php and sql, but now I want people to be able to go on the site and update their status (either in or out), any help would be great. Here is my code (which is basically an example I used, not fully understanding!) for displaying the information from the database on the website. The information from the database can be viewed and is formatted in two ways either in a simplified verision on the home page or a detailed way if the user clicks on the link. // Connect to MySQL require("../mysql.php"); $QUERY = mysql_query("SELECT ID, Name, Email, Extension, DirectDial, Status FROM contacts ORDER BY Name ASC"); if(isset($_GET['detailed'])) { echo("<tr style=\"padding:3px;\">\n\n"); echo("<td class=\"contact_field\">\n"); echo("<b>Name</b>"); echo("</td>"); echo("<td class=\"contact_field\">\n"); echo("<b>Email</b>"); echo("</td>"); echo("<td class=\"contact_field\" align=\"center\">\n"); echo("<b>Extension</b>"); echo("</td>"); echo("<td class=\"contact_field\" align=\"center\">\n"); echo("<b>Direct</b>"); echo("</td>"); echo("<td class=\"contact_field\">\n"); echo("<b>Status</b>"); echo("</td>"); echo("</tr>"); while($row = mysql_fetch_array($QUERY, MYSQL_ASSOC)) { echo("<tr style=\"padding:3px;\">\n"); echo("<td width=\"150px\" class=\"contact_field\">\n\n"); echo($row['Name'] . "\n\n"); echo("</td>\n"); echo("<td width=\"300px\" class=\"contact_field\">\n"); echo("<a href=\"mailto:" . $row['Email'] . "\">" . $row['Email'] . "</a>\n\n"); echo("</td>\n"); echo("<td width=\"100px\" align=\"center\" class=\"contact_field\">\n"); echo($row['Extension'] . "\n\n"); echo("</td>\n"); echo("<td align=\"center\" class=\"contact_field\">\n"); echo($row['DirectDial'] . "\n\n"); echo("</td>\n"); echo("<td align=\"center\" class=\"contact_field\">\n"); echo($row['Status'] . "\n\n"); echo("</td>\n"); echo("</tr>\n"); } } else { echo("<tr style=\"padding:3px;\">\n\n"); echo("<td class=\"contact_field\">\n"); echo("<b>Name</b>"); echo("</td>"); echo("<td class=\"contact_field\" align=\"center\">\n"); echo("<b>Extension</b>"); echo("</td>"); echo("<td class=\"contact_field\" align=\"center\">\n"); echo("<b>Status</b>"); echo("</td>"); echo("</tr>"); while($row = mysql_fetch_array($QUERY, MYSQL_ASSOC)) { echo("<tr style=\"padding:3px;\">\n"); echo("<td width=\"180px\" class=\"contact_field\">\n\n"); echo("<a href=\"mailto:" . $row['Email'] . "\">" . $row['Name'] . "</a>\n\n"); echo("</td>\n"); echo("<td class=\"contact_field\" align=\"center\">\n\n"); echo($row['Extension'] . "\n\n"); echo("</td>\n"); echo("<td class=\"contact_field\" align=\"center\">\n\n"); echo($row['Status'] . "\n\n"); echo("<a href=\"http://www.intertraffic.com" . $row['Status'] . "\">" . $row['Name'] . "</a>\n\n"); echo("</td>\n"); echo("</tr>\n"); } } ?> I'm having problems updating my database, I have 4 fields i want to change. I checked all the { on the page, that's not the problem, I tried to echo information from the database and it displayed my information so that's not the problem, i tried yelling at my computer, that didn't work, i tried to input data into the database with the insert function it worked but is not practical in my situation. I'm probably going to face palm when i find out whats wrong, help please btw, the $_SESSION['usr'] was set in another page and works. Code: [Select] <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Edit Info</title> <link rel="stylesheet" type="text/css" href="demo.css" media="screen" /> </head> <body> <div id="main"> <div class="container"> <font size="5" face="sans-serif">Change Settings <?php echo "{$_SESSION['usr']}"; ?></font> <form action="" method="POST"> <table cellpadding="3" cellspacinf="4" border="0"> <tr> <td>Name</td> <td><input type="text" name="name" /></td> </tr> <tr> <td>Age</td> <td><input type="text" name="age" /></td> </tr> <tr> <td>Gender</td> <td><input type="text" name="mf" /></td> </tr> <tr> <td>Location</td> <td><input type="text" name="loc" /></td> </tr> <tr> <td><input type="submit" name="submit" value="submit" /></td> </tr> </table> </form> <?php if ($_POST['submit']){ define('INCLUDE_CHECK',true); require 'connect.php'; $usr = $_SESSION['usr']; $sql = mysql_query("UPDATE members SET name='{$_POST['name']}', age='{$_POST['age']}, mf='{$_POST['mf']}', loc='{$_POST['loc']}' WHERE usr='{$_SESSION['usr']}'"); if($sql){ echo 'Changes Saved!'; }else{ echo 'Error'; } } ?> </div> </div> </body> </html> Hello all, first post here so i hope i'm doing this right and am putting this into the right place. Im in the process of integrating a blog into my website, mostly it's set up however i'm currently working on the code to update the posts (theres only 2 parts a title and a comments[which is in actual fact the post content itself]). The code succsefully completes without any errors but for some reason it does not actually update the mysql database.. the code i'm using is as follows: Code: [Select] <?php require_once('header.php'); include "../blog/blogconfig.php"; if(isset($_POST['submit'])){ $update="UPDATE eq_blogarticle SET title='".$_POST['title']."',comments='".$_POST['comment']."' WHERE artid='$aid'"; if(!mysql_query($update)){ echo mysql_error(); }else{ header("location:blog.php?action=listmsgs"); exit; } } ?> <?php // get value of aid that sent from address bar by blog.php?action=listmsgs $aid=$_GET['aid']; // Retrieve data from database $sql="SELECT * FROM eq_blogarticle WHERE artid='$aid'"; $result=mysql_query($sql); $row=mysql_fetch_array($result); ?> <form name="form2" method="post" action="update.php"> <script type="text/javascript">var SITE_URL="<?php echo SITE_URL;?>";</script> <script type="text/javascript" src="<?php echo SITE_URL;?>/includes/js/nicEdit.js"></script> <script type="text/javascript"> //<![CDATA[ bkLib.onDomLoaded(function() { nicEditors.allTextAreas() }); //]]> </script> <body> <table width="100%" border="0" cellspacing="1"> <tr> <td colspan="2" class="temptitle">Equidisc Blog</td> </tr> <tr> <td width="74%" valign="top"> <table> Edit Blog Post <br> <br> Title: <br> <input name="title" type="text" class="input" id="title" value="<? echo $row['title']; ?>"> <br> <br> <span class="style1 style2 style3">Blog Post:</span> <br> <br> <textarea name="comments" cols="55" rows="12" class="input" id="comments"><? echo stripslashes($row['comments']); ?></textarea> <br> <br> <input name="aid" type="hidden" id="aid" value="<? echo $row['artid']; ?>"> <input type="submit" name="submit" value="Submit"> </form> </table> </td> <td width="26%" valign="top"><table width="100%" border="0" cellspacing="1"> <tr> <td colspan="2"><img src="../blog/images/fb.gif" width="16" height="16" /> <strong>Blog Menu</strong></td> </tr> <tr> <td><a href="blog.php">Home</a></td> </tr> <tr> <td><a href="blog.php?action=newblogpost">New Post </a></td> </tr> <tr> <td><a href="blog.php?action=listmsgs">Manage Posts </a></td> </tr> </table></td> </tr> </table> </body> <?php require_once('footer.php'); ?> Explanation: header/footer.php obvious ../blog/blogconfig.php holds my mysql connection settings and connects to the sql, this is the same config as is used for creating the new posts which i have no issues with so i dont think the issue lays there. If i run the query on phpmyadmin with dummy data it works fine and updates the entry.. Any help would be very much appreciated as i'm at the end of my tether with this!. Thanks in advance. Jo Hello everybody, I have a script that allows a user to set themselves a target and a script that allows them to edit the target if they decide to. Now everything works as it should until the data from the form (on the edit target page) should be updated in the database. I require that the user must update at least one field. For example they may want to extend the completion date so I would only want to update the completion date field in the database and the fields the user left blank should not be updated in the database. The problem I am having is regardless of if the user enter a value into the field it updates the database so if the user leaves a field blank it updates the database will a blank value. Here is my code: //If the user clicks the update button on a WEIGHT LOSS target run the following code to update the database if(isset($_POST['target_weight_loss_update'])){ $target_weight_loss_update = $_POST['target_weight_loss_update']; $weight_loss_complete_update = $_POST['weight_loss_complete_update']; $weight_loss_comment_update = $_POST['weight_loss_comment_update']; $weight_loss_user_id_update = $_POST['weight_loss_user_id_update']; //Check that at least one value has been entered into the form if(empty($target_weight_loss_update) && empty($weight_loss_complete_update) && empty($weight_loss_comment_update)){ $error_msg = 'Please enter at least one value to update your '.$target_type.' target'; } //Check to see what variables have values in them so we know what fields to update in datebase //If the user has entered a value for their TARGET WEIGHT LOSS update that value in the database if(isset($target_weight_loss_update) || !empty($target_weight_loss_update)){ $target_weight_loss_update_sql = mysql_query("UPDATE user_targets SET target_weight='$target_weight_loss_update' WHERE id='$target_id' LIMIT 1") or die (mysql_error()); //Check that the update was successful if($target_weight_loss_update_sql){ $error_msg = 'Target '.$target_type.' updated successfully'; } else { $error_msg = 'Could not update target. Please try again.'; } } //If the user has entered a value for their TARTGET WEIGHT LOSS DATE update that value in the database if(isset($weight_loss_complete_update) || !empty($weight_loss_complete_update)){ $weight_loss_completion_date_sql = mysql_query("UPDATE user_targets SET target_date='$weight_loss_complete_update' WHERE id='$target_id' LIMIT 1") or die (mysql_error()); //Check that the update was successful if($weight_loss_completion_date_sql){ $error_msg = 'Target '.$target_type.' updated successfully'; } else { $error_msg = 'Could not update target. Please try again.'; } } //If the user has entered a value for their TARGET WEIGHT LOSS COMMENT update that value in the database if(isset($weight_loss_comment_update) || !empty($weight_loss_comment_update)){ $weight_loss_comment_update_sql = mysql_query("UPDATE user_targets SET extra_info='$weight_loss_comment_update' WHERE id='$target_id' LIMIT 1") or die (mysql_error()); //Check that the update was successful if($weight_loss_comment_update_sql){ $error_msg = 'Target '.$target_type.' updated successfully'; } else { $error_msg = 'Could not update target. Please try again.'; } } } So the question I ask is how can I stop entering blank values into the database and only update the information the user enters into the form? Also I was thinking of having one mysql query at the end and using the IF statements to build the query. Thoughts? Thanks for any advice. |