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.
Related
I need to save the count(activity_type) group by user_posted_to into a variable from mysql query
$query = "
SELECT user_posted_to, COUNT(*)
FROM activity_log_table
WHERE
post_type = 'discussion'
AND activity_type = 'Like' ";
$query .= "AND activity_timestamp >= CURRENT_DATE - INTERVAL 7 DAY AND activity_type <= CURRENT_DATE ";
$query .= "GROUP BY user_posted_to ORDER BY activity_timestamp DESC LIMIT 25";
$result = mysqli_query($connection, $query);
while ($row = mysqli_fetch_assoc($result)) {
$user_posted_to = (int)$row['user_posted_to'];
$timestamp = time();
// I need to insert the count into this table for number_assert
$query2 = "INSERT INTO top_weekly (user_id, number_assert, timestamp) VALUES ($user_posted_to, $timestamp)";
$result2 = mysqli_query($connection, $query2);
$confirm_query2 = confirm_query($result2);
if($confirm_query2) {
echo "success query 2";
} else {
echo "failed query 2";
}
}
i expect to save the count() group by into a php variable and to be able to use it later on the page
You want to alias the « COUNT(*) » to something else, like « cnt ». Then you can access the column by name after fetching, as demonstrated below :
$query = "
SELECT
user_posted_to,
COUNT(*) as cnt
FROM activity_log_table
WHERE
post_type = 'discussion'
AND activity_type = 'Like'
AND activity_timestamp >= CURRENT_DATE - INTERVAL 7 DAY
AND activity_type <= CURRENT_DATE
GROUP BY user_posted_to
ORDER BY activity_timestamp DESC
LIMIT 25";
$result = mysqli_query($connection, $query);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "user_posted_to: " . $row["user_posted_to"]. " - Count: " . $row["cnt"] . "<br>";
}
} else {
echo "0 results";
}
Add and AS label to the COUNT(*) then you will be able to readout that label in the row you get.
$query = "SELECT user_posted_to, COUNT(*) AS varCount FROM activity_log_table WHERE post_type = 'discussion' AND activity_type = 'Like' ";
$nummerOfCount = $row['varCount']
I am creating an in-house patient calendar, the clinic has more than 40K patients in the database.
I am trying to list around 9000 rows but it is taking extremely long time, I tried with 100 rows, it takes around 20 second, how can I make it much faster?
Here is my code:
$getPatients = $db->query("set names 'utf8'");
$q = "SELECT id, p_type, clinic_id, recommended_doctor, hdyhau, partnership_companies, p_auto_control_date, first_name, last_name, company, mobile, p_city, p_state, p_country, saved_by FROM dg_patients_patients WHERE clinic_id = {$defaultClinic} ORDER BY first_name ASC LIMIT 100";
$getPatients = $db->query($q);
$patientList = "";
while ($row = mysql_fetch_array($getPatients)) {
//Get Patient Type
$getPatientType = $db->query("set names 'utf8'");
$q = "SELECT * FROM dg_patient_type WHERE id = {$row['p_type']}";
$getPatientType = $db->query($q);
$patientType = mysql_fetch_array($getPatientType);
//Get Partnership Company
if($row['partnership_companies'] != '' && $row['partnership_companies'] > 0) {
$getPC = $db->query("set names 'utf8'");
$q = "SELECT * FROM dg_partnership_companies WHERE id = {$row['partnership_companies']}";
$getPC = $db->query($q);
$pc = mysql_fetch_array($getPC);
$pcname = $pc['pc_name'];
} else {
$pcname = '';
}
if(!empty($row['saved_by'])){
//Get User
$getUser = $db->query("set names 'utf8'");
$q = "SELECT * FROM dg_users WHERE id = {$row['saved_by']}";
$getUser = $db->query($q);
$user = mysql_fetch_array($getUser);
$savedby = $user['first_name'];
} else {
$savedby = '';
}
//Get Total Appointments
$q1 = "SELECT * FROM dg_appointments WHERE (appointment_type = 1 OR appointment_type =2 ) AND patient_id = {$row['id']}";
$getApps = $db->query($q1);
$totalAppointments = mysql_num_rows($getApps);
//Get Latest Appointment Date
$q11 = "SELECT * FROM dg_appointments WHERE appointment_status = 4 AND patient_id = {$row['id']} ORDER BY start_date DESC, start_time DESC LIMIT 1";
$getLastesApp = $db->query($q11);
$lastesApp = mysql_fetch_array($getLastesApp);
//Get Clinic
$getClinic = $db->query("set names 'utf8'");
$q = "SELECT * FROM dg_clinics WHERE id = {$row['clinic_id']}";
$getClinic = $db->query($q);
$clinic = mysql_fetch_array($getClinic);
//Get Doctor
if($row['recommended_doctor'] != '' && $row['recommended_doctor'] > 0) {
$getDoctor = $db->query("set names 'utf8'");
$q = "SELECT * FROM dg_users WHERE department = 2 AND id = {$row['recommended_doctor']}";
$getDoctor = $db->query($q);
$doctor = mysql_fetch_array($getDoctor);
$doctorID = $doctor['first_name'].' '.$doctor['last_name'];
} else {
$doctorID = '-';
}
//Get HDYHAU
if($row['hdyhau'] != '' && $row['hdyhau'] > 0){
$q = "SELECT * FROM dg_hdyhau WHERE id = {$row['hdyhau']}";
$getHDYHAU = $db->query($q);
$HDYHAU = mysql_fetch_array($getHDYHAU);
$HDYHAUID = $HDYHAU['hdyhau_name'];
} else {
$HDYHAUID = '-';
}
//Get Country
if($row['p_country'] != '' && $row['p_country'] > 0){
$getCountry = $db->query("set names 'utf8'");
$sql = "SELECT * FROM dg_ulke WHERE Id = {$row['p_country']}";
$getCountry = $db->query($sql);
$country = mysql_fetch_array($getCountry);
$countryID = $country['tr_TR'];
} else {
$countryID = '-';
}
//Get Cities
if($row['p_state'] != '' && $row['p_state'] > 0){
$getState = $db->query("set names 'utf8'");
$sql = "SELECT * FROM dg_il WHERE Id = {$row['p_state']}";
$getState = $db->query($sql);
$state = mysql_fetch_array($getState);
$stateID = $state['IlAdi'];
} else {
$stateID = '-';
}
//Get Streets
if($row['p_city'] != '' && $row['p_city'] > 0){
$getCity = $db->query("set names 'utf8'");
$sql = "SELECT * FROM dg_ilce WHERE Id = {$row['p_city']}";
$getCity = $db->query($sql);
$city = mysql_fetch_array($getCity);
$cityID = $city['IlceAdi'];
} else {
$cityID = '-';
}
$btn1 = "<a href='/apps/patients/patient-file.php?patientid=".$row['id']."#treatment_finance' target='_blank'><img src='/assets/images/Letter-T-blue-icon.png' width='24' height='24'></a>";
$btn2 = "<a href='/apps/patients/patient-file.php?patientid=".$row['id']."#patient_information' target='_blank'>".$row['first_name']." ".$row['last_name']."</a>";
if($lastesApp['start_date']){
$latestAppDate = date('d.m.Y', strtotime($lastesApp['start_date']));
} else {
$latestAppDate = '-';
}
if($row['p_auto_control_date'] != '' && $row['p_auto_control_date'] != '0000-00-00'){
$pacd = date('d.m.Y', strtotime($row['p_auto_control_date']));
} else {
$pacd = '-';
}
$btn5 = "<div class='checkbox checkbox-primary'><input id='checkboxPatients".$row['id']."' class='styled checkAllPatients' type='checkbox' name='checkAllPatients[]' value='".$row['id']."'><label for='checkboxPatients".$row['id']."'></label></div>";
$patientList .= "<tr>";
$patientList .= "<td>".$btn5."</td>";
$patientList .= "<td>".$clinic['clinic_name']."</td>";
$patientList .= "<td>".$btn1."</td>";
$patientList .= "<td>".$btn2."</td>";
$patientList .= "<td>".$row['mobile']."</td>";
$patientList .= "<td>".$cityID."</td>";
$patientList .= "<td>".$stateID."</td>";
$patientList .= "<td>".$row['company']."</td>";
$patientList .= "<td>".$pcname."</td>";
$patientList .= "<td>".$totalAppointments."</td>";
$patientList .= "<td>".$latestAppDate."</td>";
$patientList .= "<td>".$pacd."</td>";
$patientList .= "<td>".$savedby."</td>";
$patientList .= "<td>".$doctorID."</td>";
$patientList .= "<td>".$HDYHAUID."</td>";
$patientList .= "<td>".$countryID."</td>";
$patientList .= "</tr>";
}
echo $patientList;
You need to make index to clinic_id and first_name.
See this document http://www.w3schools.com/sql/sql_create_index.asp will help
You using too many queries in this code. reduce query will make better. use join to joining multiple table information to once, with conditions. http://www.w3schools.com/sql/sql_join_left.asp
set names utf8 only need once per code. If problem to fetching other language, checking my.cnf first to define default character set with server and connection.
use indexing in your table, index those fields which are using in where clause.
instead of use select * specify column name
instead of interacting database multiple type,fetch data from database at a time then using php show the data.
Try not using SELECT *.... instead give names of column(s) that you require and create Index on those column(s).
Warning: Just because indexing helps don't create index on all the columns cause index uses extra space
Check how to give indexing. I have attached image for you.
Syntax
ALTER TABLE `Table_name` ADD INDEX ( `Column_name` ) ;
Following are my suggestions:
1) You have 11 select queries. Out of it, 10 are in the loop and at least half of them run in the loop.
2) It means for every records in the top query, you are running 6 queries. For 100 rows, it is 600 queries (600 times database interaction). Therefore, your page is taking 20 seconds at least.
3) Again, every SQL has SELECT *, this takes more time as database tables may have number of fields.
Solution
1) Every SQL has SELECT *, use only required fields.
2) Try not to fire query in the loop.
3) Instead, get all records before loop and access them by key value array.
4) For example, the sql:
$q = "SELECT * FROM dg_users WHERE id = {$row['saved_by']}";
You can have an array of all users in array with key as user id and value as user name
And in the loop, get the value from this array like:
$savedby = isset($users[$row['saved_by']]) ? $users[$row['saved_by']] : '';
Repeat the same for all queries in the loop.
Hope, it will help you.
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!
I'm trying to order a list of items based on the amount of comments for each topic as shown below:
$page = $_GET['page'];
$query = mysql_query("SELECT * FROM topic WHERE cat_id='$page' LIMIT $start, $per_page");
if (mysql_num_rows($query)>=1)
{
while($rows = mysql_fetch_array($query))
{
$number = $rows['topic_id'];
$title = $rows['topic_title'];
$description = $rows['topic_description'];
//get topic total
$sqlcomment = mysql_query("SELECT * FROM comments WHERE topic_id='$number'");
$commentnumber = mysql_num_rows($sqlcomment);
// TRYING TO ORDER OUTPUT ECHO BY TOPIC TOTAL ASC OR DESC
echo "
<ul>
<li><h4>$number. $title</h4>
<p>$description</p>
<p>$topictime</p>
<p>$commentnumber</p>
</li>
</ul>
";
}
}
else
{
echo "<p>no records available.</p><br>";
}
What would be the best way to order each echo by $num_rows (ASC/DESC values)? NOTE: I've updated with the full code - I am trying to order the output by $commentnumber
The first query should be:
SELECT t.*, COUNT(c.topic_id) AS count
FROM topic AS t
LEFT JOIN comments AS c ON c.topic_id = t.topic_id
WHERE t.cat_id = '$page'
GROUP BY t.topic_id
ORDER BY count
LIMIT $start, $per_page
You can get $commentnumber with:
$commentnumber = $rows['count'];
You don't need the second query at all.
First of all you have error here
echo "divs in order from least to greatest "number = $num_rows"";
It should be
echo "divs in order from least to greatest number = " . $num_rows . "";
And about the most commented try with
$sql = "SELECT * FROM `table` WHERE `id` = '$id' ORDER BY column DESC/ASC";
Or if there is not count column try with
$sql = "SELECT * FROM `table` WHERE `id` = '$id' ORDER BY COUNT(column) DESC/ASC";
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.