Too many Database Calls - php

I have an auto refresh script that refreshes a page every 3 seconds. The page it refreshes ha few database queries. When I get 20 or more members on my site the server crashes because of all the calls to the database. Is there another way to check for changes in the database?
//Can't Chat
$strFind="SELECT * FROM cantchat";
$result=mysql_query($strFind) or die(mysql_error());
while($row=mysql_fetch_array($result))
{
$id=$row['memid'];
$strsql="DELETE FROM cometchat_chatroommessages WHERE userid=\"$id\"";
$chkrow1=mysql_query($strsql,$connect) or die(mysql_error());
}
if($banned<1){
$strFind="SELECT * FROM ttourmember WHERE memberid=\"$curmemid\"";
$result=mysql_query($strFind) or die(mysql_error());
$row=mysql_fetch_array($result);
$membername=$row['membername'];
$console=$row['system'];
# timeout - how long should it take before visitors are no longer 'online'? (in minutes)
define ('timeout', 20);
// check if visitor is already in the table
$lastactive =time();
$strFind="SELECT COUNT(*) AS total FROM online WHERE `memberid`=\"$curmemid\"";
$result=mysql_query($strFind) or die(mysql_error());
$row=mysql_fetch_array($result);
$imonline=$row['total'];
if ($imonline<1) {
// Insert new visitor
$strsql="INSERT INTO online(lastactive,memberid,membername,console,ipaddress,accountactive) VALUES(\"$lastactive\",\"$curmemid\",\"$membername\",\"$console\",\"$ip\",'Y')";
$chkrow1=mysql_query($strsql,$connect) or die(mysql_error());
$onlineid=mysql_insert_id();//copied
} else {
// Update exisiting visitor
$strsql="UPDATE online SET `lastactive`=\"$lastactive\",membername=\"$membername\",console=\"$console\",ipaddress=\"$i p\" WHERE `memberid`=\"$curmemid\"";
mysql_query($strsql,$connect) or die(mysql_error());
$chkrow5=mysql_affected_rows($connect);
$strsql="UPDATE ttourmember SET `ipadd`=\"$ip\" WHERE `memberid`=\"$curmemid\"";
mysql_query($strsql,$connect) or die(mysql_error());
$chkrow5=mysql_affected_rows($connect);
}
// Remove any inactive visitors
$inactive = time()-21;
//Who's Online list
$strFind="SELECT * FROM online WHERE lastactive< $inactive AND `stay`<>'Y'";
$result=mysql_query($strFind) or die(mysql_error());
while($row=mysql_fetch_array($result))
{
$friendid=$row['memberid'].",";
$strsql="DELETE FROM friends WHERE toid=\"$friendid\" OR fromid=\"$friendid\"";
$chkrow1=mysql_query($strsql,$connect) or die(mysql_error());
}
$strsql="DELETE FROM online WHERE lastactive < $inactive AND stay<>'Y'";
mysql_query($strsql,$connect) or die(mysql_error());
$chkrow5=mysql_affected_rows($connect);
//Can Chat
$query_chat = "SELECT * FROM online WHERE `memberid`<>\"$curmemid\" ORDER BY membername DESC";
$chat = mysql_query($query_chat) or die(mysql_error());
$row_chat = mysql_fetch_assoc($chat);
$totalRows_chat = mysql_num_rows($chat);
//Count Pending Games
$strFind="SELECT COUNT(*) AS total FROM tgamertournament WHERE `memberid` = \"$curmemid\" AND `pending`='Y'";
$result=mysql_query($strFind) or die(mysql_error());
$row=mysql_fetch_array($result);
$tpgames=$row['total'];
$strFind="SELECT COUNT(*) AS total FROM tgamertournament WHERE `targetto` = \"$curmemid\" AND `pending`='Y'";
$result=mysql_query($strFind) or die(mysql_error());
$row=mysql_fetch_array($result);
$topgames=$row['total'];
$pgames=$tpgames+$topgames;
//Steam Received Sent Challenge
$query_stgames = "SELECT * FROM tgtournamentrequest WHERE `gamer`=\"$curmemid\" AND `active`<>'D' AND `scored`<>'Y' AND `type`='S' AND `startfteam`='Y' AND `isaccepted`='N' AND `startsteam`='N' ORDER BY tournamentid DESC LIMIT 3";
$stgames = mysql_query($query_stgames) or die(mysql_error());
$row_stgames = mysql_fetch_assoc($stgames);
$totalRows_stgames = mysql_num_rows($stgames);
//Waiting For Fteam Sent Challenge To Get Accepted
$query_wftgames = "SELECT * FROM tgtournamentrequest WHERE `fteam`=\"$curmemid\" AND `active`<>'D' AND `scored`<>'Y' AND `type`='S' AND `startfteam`='Y' AND `isaccepted`='N' AND `startsteam`='N' ORDER BY tournamentid DESC LIMIT 3";
$wftgames = mysql_query($query_wftgames) or die(mysql_error());
$row_wftgames = mysql_fetch_assoc($wftgames);
$totalRows_wftgames = mysql_num_rows($wftgames);
//List Posted Pending Games Accepted
$query_apostedgames = "SELECT * FROM tgtournamentrequest WHERE `gamer` = \"$curmemid\" OR `fteam`=\"$curmemid\" AND `active`<>'D' AND `scored`<>'Y' AND `type`='P' ORDER BY tournamentid DESC LIMIT 3";
$apostedgames = mysql_query($query_apostedgames) or die(mysql_error());
$row_apostedgames = mysql_fetch_assoc($apostedgames);
$totalRows_apostedgames = mysql_num_rows($apostedgames);
//List Posted Pending Games
$query_postedgames = "SELECT * FROM tgtournamentrequest WHERE `gamer` = \"$curmemid\" OR `fteam`=\"$curmemid\" AND `active`<>'D' AND `scored`<>'Y' AND `type`='P' ORDER BY tournamentid DESC LIMIT 3";
$postedgames = mysql_query($query_postedgames) or die(mysql_error());
$row_postedgames = mysql_fetch_assoc($postedgames);
$totalRows_postedgames = mysql_num_rows($postedgames);
//Report Score
$query_score = "SELECT * FROM tgtournamentrequest WHERE `fteam` = \"$curmemid\" AND `gamer`<>'0' AND `isaccepted`='Y' AND `active`='Y' AND `startfteam`='Y' AND `startsteam`='Y' AND `scored` <>'Y' ORDER BY tournamentid DESC LIMIT 3";
$score = mysql_query($query_score) or die(mysql_error());
$row_score = mysql_fetch_assoc($score);
$totalRows_score = mysql_num_rows($score);
//Steam Pending Score
$query_pscore = "SELECT * FROM tgtournamentrequest WHERE `gamer` = \"$curmemid\" AND `fteam`<>'0' AND `active`='Y' AND `startfteam`='Y' AND `startsteam`='Y' AND scored <>'Y' ORDER BY tournamentid DESC LIMIT 3";
$pscore = mysql_query($query_pscore) or die(mysql_error());
$row_pscore = mysql_fetch_assoc($pscore);
$totalRows_pscore = mysql_num_rows($pscore);
//Delete Games
$query_dmoline = "SELECT * FROM tgamertournament WHERE `memberid` = \"$curmemid\" AND `deleted`<>'Y' AND `scored`<>'Y' AND `accepted` <>'Y' AND `targetto`='0' AND `isactive`='Y'";
$dmoline = mysql_query($query_dmoline) or die(mysql_error());
$row_dmoline = mysql_fetch_assoc($dmoline);
$totalRows_dmoline = mysql_num_rows($dmoline);

Well, first of all I wouldn't do the following:
$strFind="SELECT * FROM online WHERE lastactive< $inactive AND `stay`<>'Y'";
$result=mysql_query($strFind) or die(mysql_error());
while($row=mysql_fetch_array($result))
{
$friendid=$row['memberid'].",";
$strsql="DELETE FROM friends WHERE toid=\"$friendid\" OR fromid=\"$friendid\"";
//echo $strsql;
//exit;
$chkrow1=mysql_query($strsql,$connect) or die(mysql_error());
}
Instead grab all the id's and delete them at once. I'd also only fetch the one column I need to do this:
$strFind="SELECT memberid FROM online WHERE lastactive< $inactive AND `stay`<>'Y'";
$result=mysql_query($strFind) or die(mysql_error());
$offline = array();
while($row=mysql_fetch_array($result))
{
$offline[]="'{$row['memberid']}'";
}
$friendids = implode(',', $offline);
$strsql="DELETE FROM friends WHERE toid IN ($friendids) OR fromid IN ($friendids)";
$chkrow1=mysql_query($strsql,$connect) or die(mysql_error());

Is there another way to check for changes in the database?
Try show processlist in phpMyAdmin or a mysql-shell while your site is "under attack"... you should see the running queries and how long they are running. Maybe you find some heavy queries.

Related

If value from database on user is 0 then execute php code

Hi guys i'm quite new to PHP but I'm currently working on this site and I want it to check if the total_online_time for the user is 0 or less then it should execute the script which will create a room for the user. However after trying with this script the .php page won't load.
http://pastebin.com/XDLhFvtE
<?php
$getStats = mysql_query("SELECT total_online_time FROM `users` WHERE id = '".$_SESSION['user']['id']."'");
if ($getStats > 0)
$getRoomKit = mysql_fetch_assoc(mysql_query("SELECT * FROM room_starterkit ORDER BY RAND() LIMIT 1"));
$getRoom = mysql_fetch_assoc(mysql_query("SELECT * FROM `rooms` WHERE id = '".$randomRoomID['id']."' LIMIT 1"));
$welcomeMessage = "Welcome " . $_SESSION['user']['username'];
mysql_query("INSERT INTO `rooms` (caption,owner_id,description,model_name,wallpaper,floor) VALUES ('".$welcomeMessage."', '".$_SESSION['user']['id']."', 'Welcome to Hablore', '".$getRoomKit['room_Model']."', '".$getRoomKit['room_Wallpaper']."', '".$getRoomKit['room_Floor']."') ");
$theRoomID = mysql_fetch_assoc(mysql_query("SELECT id FROM `rooms` ORDER BY `id` DESC LIMIT 1"));
mysql_query("UPDATE `users` SET `home_room` = '".$theRoomID['id']."' WHERE `id` = '".$_SESSION['user']['id']."'");
$getRoomItems = mysql_query("SELECT * FROM room_itemkits WHERE roomKit = '".$getRoomKit['id']."'");
while($CurItem = mysql_fetch_assoc($getItems)){
mysql_query("INSERT INTO `items` (user_id, room_id, base_item, extra_data, x, y, z, rot, wall_pos) VALUES ('".$_SESSION['user']['id']."','".$lastRoomID['id']."','".$CurItem['base_item']."','".$CurItem['extra_data']."','".$CurItem['x']."','".$CurItem['y']."','".$CurItem['z']."','".$CurItem['rot']."','".$CurItem['wall_pos']."')");
}
}
?>

Multiple SQL If statements within PHP While loops

I've created a script to run on my database at five minute intervals as a cron job. It's not a well written piece of code, but it's done quickly and should do the job for now.
I'm executing a WHILE loop to execute multiple if statements which in turn have multiple SQL statements within them. Problem is, it's only iterating the WHILE loop once and then stops and i'm not entirely sure why. Code is as below:
<?php
require_once('config.php');
$hashtags = mysql_query("SELECT id, hashtag FROM hashtags WHERE enabled = '1'") or die(mysql_error());
while($row = mysql_fetch_array($hashtags))
{
$hashtag_id = $row['id'];
$hashtag = $row['hashtag'];
//Get id and latest_tweet_id from report log
$latest_report_tweet_id_query = mysql_query("SELECT id, latest_tweet_id FROM reports_log WHERE name = 'post_count' AND hashtag_id = '".$hashtag_id."' LIMIT 1") or die(mysql_error());
if (mysql_num_rows($latest_report_tweet_id_query) == 0) {
$new_report_tweet_id_query = mysql_fetch_array(mysql_query("SELECT tweet_id FROM tweet_tags WHERE tag = '".$hashtag."' ORDER by tweet_id desc LIMIT 1")) or die(mysql_error());
$new_report_tweet_id = $new_report_tweet_id_query['tweet_id'];
$post_count_query = mysql_fetch_array(mysql_query("SELECT count(tweet_id) as tweet_count FROM tweet_tags WHERE tag = '".$hashtag."' AND tweet_id <= '".$new_report_tweet_id."'")) or die(mysql_error());
$post_count = $post_count_query['tweet_count'];
if(mysql_query("INSERT INTO post_count_reports (timestamp, hashtag_id, post_count, latest_tweet_id) VALUES ('".date("Y-m-d H:i:s")."', '".$hashtag_id."', '".$post_count."', '".$new_report_tweet_id."')"))
{
//Get just created id of the report
$report_id_query = mysql_fetch_array(mysql_query("SELECT id FROM post_count_reports WHERE hashtag_id = '".$hashtag_id."' AND latest_tweet_id = '".$new_report_tweet_id."'")) or die(mysql_error());
$report_id = $report_id_query['id'];
if(mysql_query("INSERT INTO reports_log (timestamp, hashtag_id, name, latest_tweet_id, latest_report_id) VALUES ('".date('Y-m-d H:i:s')."', '".$hashtag_id."', 'post_count', '".$new_report_tweet_id."', '".$report_id."')"))
{
echo "Successfully created report! NEW";
}
else {
echo "Failed updating report log! NEW";
}
}
else
{
echo "Failed making report! NEW";
}
}
else {
//Set the latest report id
$latest_report_tweet_id_array = mysql_fetch_array($latest_report_tweet_id_query);
$latest_report_log_id = $latest_report_tweet_id_array['id'];
$latest_report_tweet_id = $latest_report_tweet_id_array['latest_tweet_id'];
//Query to get the latest tweet_id in the database
$new_report_tweet_id_query = mysql_fetch_array(mysql_query("SELECT tweet_id FROM tweet_tags WHERE tag = '".$hashtag."' ORDER by tweet_id desc LIMIT 1")) or die(mysql_error());
$new_report_tweet_id = $new_report_tweet_id_query['tweet_id'];
//Query to get the new post count from database
$new_post_count_query = mysql_fetch_array(mysql_query("SELECT count(tweet_id) as tweet_count FROM tweet_tags WHERE tag = '".$hashtag."' AND tweet_id > '".$latest_report_tweet_id."' AND tweet_id <= '".$new_report_tweet_id."'")) or die(mysql_error());
$new_post_count = $new_post_count_query['tweet_count'];
$old_post_count_query = mysql_fetch_array(mysql_query("SELECT id, post_count FROM post_count_reports ORDER by timestamp desc LIMIT 1")) or die(mysql_error());
$old_post_count = $old_post_count_query['post_count'];
$post_count = $old_post_count + $new_post_count;
if(mysql_query("INSERT INTO post_count_reports (timestamp, hashtag_id, post_count, latest_tweet_id) VALUES ('".date('Y-m-d H:i:s')."', '".$hashtag_id."', '".$post_count."', '".$new_report_tweet_id."')"))
{
//Get just created id of the report
$report_id_query = mysql_fetch_array(mysql_query("SELECT id FROM post_count_reports WHERE hashtag_id = '".$hashtag_id."' AND latest_tweet_id = '".$new_report_tweet_id."' ORDER by timestamp desc LIMIT 1")) or die(mysql_error());
$report_id = $report_id_query['id'];
if(mysql_query("UPDATE reports_log SET id = '".$latest_report_log_id."', timestamp = '".date('Y-m-d H:i:s')."', latest_tweet_id = '".$new_report_tweet_id."', latest_report_id = '".$report_id."' WHERE name = 'post_count'"))
{
echo "Successfully created report!";
}
else {
echo "Failed updating report log!";
}
}
else
{
echo "Failed making report!";
}
}
}
?>
Massive error on my part, turns out whilst there were three hashtags in the hashtags table there were only rows with one of the hashtags in the tweet_tags table. Wasted a few hours on this one.
Moral of the story, always log and check for errors!

Creating arrays from Mysql queries inside a foreach loop

I am trying to populate a table displaying statistics. I have a list of campaign id's have been placed into an array using the following query:
$query = "SELECT `id` FROM `c_templates` ORDER BY `id`";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$id[] = $row['id'];
}
Once I have all of my id's, I am using a foreach loop to make 5 queries per id gathering all the table data.
foreach($id as $i){
// sent
$query = "SELECT `template`, COUNT(*) as count FROM `s_log` WHERE `template` = '".$i."' AND `time_sent` BETWEEN '".$start."' AND '".$stop."'";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$template[] = $row['template'];
$count[] = $row['count'];
}
// opens
$query = "SELECT COUNT(*) as count FROM `t_opens` WHERE `campaign_id` = '".$i."' AND `timestamp` BETWEEN '".$start."' AND '".$stop."'";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$opens[] = $row['count'];
}
// clicks
$query = "SELECT `campaign_id`, COUNT(*) as count FROM `t_analytics` WHERE `campaign_id` = '".$i."' AND `timestamp` BETWEEN '".$start."' AND '".$stop."'";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$click_count[] = $row['count'];
}
// conversions
$query = "SELECT `conversion_value`, COUNT(*) as count FROM `t_analytics` WHERE `campaign_id` = '".$i."' AND `timestamp` BETWEEN '".$start."' AND '".$stop."' AND `conversion_value` > 0";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$conversion_value[] = $row['conversion_value'];
$conversion_count[] = $row['count'];
}
// bounce rate
$query = "SELECT COUNT(*) AS `ck` FROM `s_log` WHERE `time_sent` BETWEEN '".$start."' AND '".$stop."' AND `status` = 'hardbounce' OR `status` = 'softbounce' AND `template` = '".$i."'";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$bounce_count[] = $row['ck'];
}
}
The issue is that this process takes 4-5 seconds to perform over 40-50 id records. I placed some timers after each query to confirm the queries were performing correctly and they were. I ran OPTIMIZE and double checked to be sure everything was properly indexed. As far as I can tell, the issue is not in mysql.
The only thing I could find is that there is a .1-.5 second delay after each loop cycle. When trying to run 40-50 rows, this definitely begins to add up.
My question: Is there a better and faster way to fetch this data? Is there something else I should be checking to speed the process up?
The only solution I could think of was to run one query for each statistic (5 total queries) fetching the data for all id and placing them in a array for later display. I'm not sure how that could be done or if it's even possible. It seems to me I would have to run a separate query for each id, but I'm hoping I'm wrong.
Any help will be greatly appreciated!!

Need to order and grab SQL rows by 2 criteria

I am using the following PHP and MySQL code to pull high score records out of a database, 5 above and 5 below the users score.
<?php
$dbcon = mysql_connect("localhost", "XXXX", "XXXX") or die(mysql_error());
mysql_select_db("tulesblo_koreangame", $dbcon) or die(mysql_error());
mysql_query("SET NAMES utf8");
$name = $_POST["name"];
$email = $_POST["email"];
$score = $_POST["score"];
$table = "";
$submit = "";
$input = "";
$newposition = $_POST['position'];
$position = mysql_query("(SELECT position
FROM highscore
WHERE score < '$score'
ORDER BY score DESC
LIMIT 1)");
if(!$name){
$gethigherrows = "(SELECT *
FROM highscore
WHERE score >= '$score'
ORDER BY score ASC
LIMIT 5)";
$getlowerrows = "(SELECT *
FROM highscore
WHERE score < '$score'
ORDER BY score DESC
LIMIT 5)";
$higherrows= mysql_query($gethigherrows);
$lowerrows= mysql_query($getlowerrows);
if(mysql_error())echo mysql_error();
while($row=mysql_fetch_array($higherrows))
{
$uppertable .= "<tr><td>$row[position]</td><td>$row[name]</td> <td>$row[score]</td></tr>";
}
$x = 0;
if (mysql_num_rows($lowerrows) > 0)
{ mysql_query("UPDATE highscore SET position = position + 1 WHERE score < '$score'")or die("update failed");
while($row=mysql_fetch_array($lowerrows))
{
if ($x == 0)
{$position = $row['position'];};
$x++;
$newpos = $row[position]+1;
$lowertable.= "<tr><td>$newpos</td><td>$row[name]</td> <td>$row[score]</td></tr>";
}
$input = "<tr><td id='position'>$position</td><td><input id='nameinput'type='text' /></td><td>$score</td></tr>";
$submit = "<br />Enter email if you want to receive a prize!<br /><input id='emailinput'type='text' /><br /><input id='submithighscore'type='submit' value='Submit'>";
}
$table .= "<table id='scoretable'><tr><th>Position</th><th>Name</th><th>Score</th></tr>";
$table .= $uppertable;
$table .= $input;
$table .= $lowertable;
$table .= "</table>";
$table .= $submit;
$table .= "<br /><span class='msg'></span>";
echo $table;
}else{ echo($newposition);
mysql_query("INSERT INTO highscore VALUES (NULL, '$score', '$name', '$email', '$newposition')");
}
?>
The only problem, as you can see, is that if there are several instances of the same score, as there are and inevitably will be, the positions get jumbled up. How can I select by score first but ensure that it grabs the positions in a sensible order?
EDIT: OK, using the following
$gethigherrows = "(SELECT *
FROM highscore
WHERE score >= '$score'
ORDER BY
position ASC
LIMIT 5)";
$getlowerrows = "(SELECT *
FROM highscore
WHERE score < '$score'
ORDER BY score DESC,
position DESC
LIMIT 5)";
I now get:
Which is better but the above scores really need to be 9,8,7,6,5
Honestly SQL fries my brain :P
You can specify more than one column in a ORDER BY clause.
ORDER BY score ASC, position DESC
First I would fix those SQL-injection holes:
$score = mysql_real_escape_string($_POST['score']);
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']);
$sql = "(SELECT *
FROM highscore
WHERE score >= '$score'
ORDER BY score ASC, position DESC
LIMIT 5)";
If you don't I can substitude ' or (1=1) LIMIT 1 UNION SELECT password, email, username FROM users -- for score. To get a list of all passwords and email addresses of your users.

How to get the player rank from there stats in php and mysql

I have the following code i am trying to get the play speed rank from mysql.
Mysql Table Called Accounts
Username | Speed
-----------------
Player1 21
Player2 52
Player3 33
Player2 52(Ranked:1)
Player3 33(Ranked:2)
Player2 21(Ranked:3)
$result = mysql_query("SELECT * FROM accounts") or die (mysql_error());
while($row = mysql_fetch_array($result)) {
$username= $row[username];
$speed = $row['speed'];
}
sorry i have been trying different ways but i cant get it to work
Why not simply:
$result = mysql_query("SELECT * FROM accounts ORDER BY speed DESC") or die (mysql_error());
$rank = 1;
while($row = mysql_fetch_array($result)) {
$username= $row[username];
$speed = $row['speed'];
$rank++;
}
Use it:
$result = mysql_query("SELECT * FROM accounts ORDER BY speed DESC") or die (mysql_error());
Just sort them by speed:
$result = mysql_query("SELECT * FROM accounts ORDER BY speed DESC") or die (mysql_error());
$prev_rank = 0;
while($row = mysql_fetch_array($result)) {
$username= $row['username'];
$speed = $row['speed'];
$rank = ++$prev_rank;
}
Read about ORDER BY.

Categories