I want to make a mysql query after a few seconds the website user has performed an action on my website. I think I can do it with php sleep, but i don't know if it is the best way to do it. What are the options for doing that?
Thanks for your answers.
Edited:
The idea is: I have a lobby, where website registered users can join (When they join a mysql query is performed updating the info on their sql row, setting that they are connected to lobby number x, and on slot x, but they aren't joined to the server). When they join to the lobby i want to give them x time (suppose 5 minutes) to join a counter strike source server (This updates the user row setting that they are joined to the server). But, i want to kick them of the lobby (this is just updating again their row in the mysql database), if in those 5 minutes they haven't joined the server. I got all of this coded except the part of wait 5 minutes and check if they are connected.
The code is:
$PlayerSlot=mysql_real_escape_string($_POST['playern']);
$sID = mysql_real_escape_string($_POST['jsID']);
//Check if actual player is already in another lobby
$query = sprintf("SELECT `playern` FROM `WebsiteUsers` WHERE `userID`='%s'", mysql_real_escape_string($_SESSION['userID']));
$result = mysql_query($query, $con) or die("Error checking user state: ".mysql_error());
$row = mysql_fetch_row($result);
$playerPlaying = $row[0];
//Check if the slot is free
$query = "SELECT `".$PlayerSlot."` FROM `ServerPlayers`";
$result = mysql_query($query, $con);
$PlayerSlotFree = mysql_fetch_row($result);
if($playerPlaying == NULL && $PlayerSlotFree[0] == NULL) {
$query = "UPDATE `WebsiteUsers` SET `playern`='".$PlayerSlot."', `servern`='".$sID."' WHERE `userID`='".$_SESSION['userID']."'";
$result = mysql_query($query, $con) or die(mysql_error());
$query = "UPDATE `ServerPlayers`SET `".$PlayerSlot."`='".$_SESSION['userID']."', WHERE `serverID`='".$sID."'";
$result = mysql_query($query, $con) or die(mysql_error());
//Update Current Players
$query = "UPDATE `Servers` SET `serverPlayers`=serverPlayers + 1 WHERE `serverID`='".$sID."'";
$result = mysql_query($query, $con) or die(mysql_error());
//TO-DO Here Wait 5 minutes and perform another query
}
Use setTimeout() in javascript
// Wait for 3 Seconds then execute
setTimeout(function(){
// your action
}, 3000);
// In Every 3 Second Execute
setInterval(function(){
// your action
}, 3000);
Related
I am creating a website in php. I have a database called database1 I have the tables cooldown and my_table The cooldown table contains the columns time(type Timestamp default value CURRENT_TIMESTAMP) and ip(type int(30) default value none). At the end of my code I have mysqli_query($conn, "DELETE FROM cooldown WHERE time < NOW() - INTERVAL 5 MINUTE"); which should delete the row after 5 minutes, but it doesn't delete the row. Could this be because the user gets redirected so the php script stops working? Or do I miss something else?
Code:
//Test if it is a shared client
if (!empty($_SERVER['HTTP_CLIENT_IP'])){
$ip=$_SERVER['HTTP_CLIENT_IP'];
//Is it a proxy address
}elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}else{
$ip=$_SERVER['REMOTE_ADDR'];
}
//The value of $ip at this point would look something like: "192.0.34.166"
$ip = ip2long($ip);
//The $ip would now look something like: 1073732954
$query = mysqli_query($conn, "SELECT ip FROM cooldown WHERE ip = '$ip'");
$row = mysqli_fetch_array($query);
if ($row) {
//What page shall the bans be sent to?
header("Location: http://imnothere.epizy.com/cooldown.html"); //cooldownpage
exit();
} else {
$sql1= "SELECT links FROM my_table WHERE Type = 'spotify' ORDER BY RAND() LIMIT 1";
$result1 = $conn->query($sql1); //this actually runs the query on the DB, and comes back with a $result object
if($result1 === false) {
echo $conn->error();
}
$redirect = $result1->fetch_assoc()['links']; //this gets one row from the $result object, and then the 'links' column from that row.
header("Location: " . $redirect);
$sql = "INSERT INTO cooldown(ip, time) VALUES('$ip', NOW())";
$result = $conn->query($sql); //this actually runs the query on the DB, and comes back with a $result object
if($result === false) {
}
mysqli_query($conn, "DELETE FROM cooldown WHERE time < NOW() - INTERVAL 5 MINUTE");
}
Your SQL query won't delete the rows after 5 minutes, it will delete everything that is 5 minutes or older at the time of the request.
You're probably best moving that line of code to a separate file that is run by cron or setup an event in your db to do it say every minute or so.
U can with Cron job , supervisor or schedule time
Your SQL query almost as it
DELETE FROM cooldown WHERE time < NOW() - INTERVAL 5 MINUTE
If you want every five minutes, use either
*/5 * * * * fooo
I have a user registration and login system that initially sets first date and time registered. Each time a user logs in i have a query that checks the time difference between the registered datetime and the current time now. if the difference in time is greater than or equal to 180seconds add 10 to the rating column of that user and reset current time of login as the new datetime/registered datetime, then redirect the user to index page.
If the time difference is less than 180 seconds just redirect the user to index page without adding a number to the rating table.
I have tried many codes did research on how to get this working all i see is cron job. i dont want to do this with cron job.
there has to be a way, please help. you guys need to save me.
This is what i have done
<?php
// This is part of the code
//$_SESSION['id'] = $id;
$_SESSION['email'] = $email;
date_default_timezone_set("Africa/Lagos");
// getting the time query difference
$sql1 = "SELECT TIMESTAMPDIFF(SECOND, date, NOW()) AS tdif FROM
users WHERE email='$email'";
$result = $con->prepare($sql1);
$result->execute();
$result->bind_result($tdif);
$result->fetch();
//var_dump($tdif);
if ($tdif >= 180) {
//following code suppose run once every 180seconds
//update user's page rank
$sql2 = "UPDATE users SET rating = rating + 10 WHERE email='$email'";
$result2 = $con->query($sql2) or die("Unable to select and run query");
//update last execution time
$sql3 = "UPDATE users SET date = NOW() WHERE email='$email'";
$result3 = $con->query($sql3) or die("Unable to select and run query");
}
//login me in
redirectToIndexPage();
// This Outputs Unable to select and run query
?>
This code just add 10 to the rating irrespective of the time difference all the time.
in other words it keeps adding 10 each time the user logs in which is suppose to happen only after 3mins(180seconds) from last login or registered datetime
Please help i know am getting something wrong.
As stated in the comments above you are not getting back a single value from your query as expected. The modified code below will do the same query and set your $tdif variable to a single value that will work in your if statement.
$sql1 = "SELECT TIMESTAMPDIFF(SECOND, date, NOW()) AS tdif FROM users WHERE email=?";
$result = $con->prepare($sql1);
$resylt->bind_param("s",$email);
$result->execute();
$result->bind_result($tdif);
$result->fetch();
if ($tdif >= 180) {
//update user's page rank
$sql2 = "UPDATE users SET rating = rating + 10 WHERE email='$email'";
$result2 = $con->query($sql2) or die("Unable to select and run query");
//update last execution time
$sql3 = "UPDATE users SET date = NOW() WHERE email='$email'";
$result3 = $con->query($sql3) or die("Unable to select and run query");
}
redirectToIndexPage();
I am displaying data from database, but I want to display one time same id but in other column how many times its stored in MySQL database.
Thanks!
if (!isset($_REQUEST['completed_consu_id'])) {
$query = "SELECT * FROM completed_consumers";
} else {
$query = "SELECT * FROM completed_consumers WHERE consu_id=consu_id";
}
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
$numberofrow=mysql_num_rows($result);
while ($row = #mysql_fetch_array($result)) {
$consu_id = $row['consu_id'];
$consu_first_name = $row['consu_first_name'];
$consu_last_name = $row['consu_last_name'];
$consu_phone = $row['consu_phone'];
$consu_email = $row['consu_email'];
$consu_address = $row['consu_address'];
$consu_city = $row['consu_city'];
$consu_state = $row['consu_state'];
$consu_zip = $row['consu_zip'];
$consu_IP = $row['consu_IP'];
$status = $row['status'];
$query2 ="SELECT consu_id, COUNT(*) FROM completed_consumers WHERE consu_id=$consu_id GROUP BY consu_id";
$result2 = mysql_query($query2) or die('Query failed: ' . mysql_error());
$numberofrow2=mysql_num_rows($result2);
$times= $numberofrow2;
echo $times;
This is code i have written, Its displaying all the consumers details and how many they have entered data or details, but I want to show one time consumer details/Name but how many time they submitted data in "times" column.
Like David consumer added 2 times, Monika added 1 time, Arshi added 3 times data/details, but when i retrieve data its showing 6 rows in table, i want to show in 3 row, 1 for David, 1 for Monika, 1 for Arshi but with how many times they added in "times" column when i retrieve it details.
Take a look at the GROUP BY clause.
SELECT id, COUNT(*) FROM completed_consumers WHERE consu_id=$consu_id GROUP BY consu_id
The below script is called every 5 seconds. The issue is that if the server is responding slow, one entry in "blog" can get selected twice in a row because the server hasn't had time to set "done" to "1" yet. Is there an industry standard (or whatever you call it) way to prevent this from happening?
$result = mysql_query("SELECT * FROM blogs WHERE done=0 LIMIT 1");
$rows = mysql_num_rows($result); //If there are no entries in with done set to 0, that means we've done them all; reset all entries to 0.
if($rows == 0)
{
mysql_query("UPDATE blogs SET done=0 WHERE done=1");
}
else
{
while($row = mysql_fetch_array($result))
{
mysql_query("UPDATE blogs SET done=1 WHERE id=$row[id]");
// Do stuff
}
}
I think I could change it to
while($row = mysql_fetch_array($result))
{
if($row['done'] == 1){ die; }
mysql_query("UPDATE blogs SET done=1 WHERE id=$row[id]");
//Do stuff
}
But will that really fix the problem? I would imagine there would be a better way that really prevents it from happening without a shadow of a doubt.
I think the best way to prevent selecting the same row is using SELECT GET_LOCK("lock_name"); and SELECT RELEASE_LOCK("lock_name");. When you get a lock from mysql server, other processing trying to get a lock will wait for the lock to be released. Below is a sample implementation:
<?php
function getLock($lockName, $dbc) {
$query = "SELECT GET_LOCK('".$lockName."', 0)";
$result = mysql_query($query, $dbc);
$lockResult = mysql_fetch_row($result);
$lockResult = $lockResult[0];
return $lockResult == 1 ? true : false;
}
function releaseLock($lockName, $dbc) {
$query = "SELECT RELEASE_LOCK('".$lockName."')";
$result = mysql_query($query, $dbc);
}
// CONNECT TO DATABASE
$dbc = mysql_connect('localhost', 'root', '');
mysql_select_db('test', $dbc);
$loopQueue = true;
$rowsProcessed = 0;
// MAIN QUEUE LOOP
while ($loopQueue) {
// TRY UNTIL GETTING A LOCK
$queueLockName = 'queue_lock_1';
while (getLock($queueLockName, $dbc) === true) {
// WE GOT THE LOCK, GET A QUEUE ROW WITH PENDING STATUS
$query = 'SELECT * FROM test WHERE status = 0 ORDER BY ID ASC LIMIT 1';
$result = mysql_query($query, $dbc);
if (mysql_num_rows($result) < 1) {
// SINCE WE DON"T HAVE ANY QUEUE ROWS, RELEASE THE LOCK
releaseLock($queueLockName, $dbc);
// WE DONT NEED TO LOOP THE MAIN QUEUE ANYMORE SINCE WE DONT HAVE ANY QUEUE ROWS PENDING
$loopQueue = false;
// BREAK THIS LOOP
break;
}
// WE GOT THE QUEUE ROW, CONVERT IT TO ARRAY
$queueRowArray = mysql_fetch_assoc($result);
// UPDATE QUEUE ROW STATUS TO SENDING
$query = 'UPDATE test SET status = 1 WHERE id = '.$queueRowArray['id'];
mysql_query($query);
// RELEASE THE LOCK SO OTHER JOBS CAN GET QUEUE ROWS
releaseLock($queueLockName, $dbc);
// DO STUFF ...
// UPDATE QUEUE ROW STATUS TO PROCESSED
$query = 'UPDATE test SET status = 2 WHERE id = '.$queueRowArray['id'];
mysql_query($query);
$rowsProcessed++;
}
}
echo "\n\n".'process finished ('.$rowsProcessed.')'."\n\n";
I would have given a go to transactions. Here is an example in another StackOverflow question
Just a question: What happens if the server is even slower? For instance, the select statament takes so long (e.g. 5 seconds) that once it finishes (returning 0 rows), the new select is executed (returning 1 or more rows)
MySQL documentation
$result = mysql_query("SELECT * FROM blogs WHERE done=0 LIMIT 1");
$rows = mysql_num_rows($result); //If there are no entries in with done set to 0, that means we've done them all; reset all entries to 0.
if($rows == 0)
{
mysql_query("UPDATE blogs SET done=0 WHERE done=1");
}
else
{
while($row = mysql_fetch_array($result))
{
mysql_query("UPDATE blogs SET done=1 WHERE id=$row[id] AND done=0");
if(mysql_affected_rows() != 1)
die();
// Do stuff
}
}
I am running a PHP script which basically tries to find matching names from MYSQL database and then assigns the same number to records with identical names.
My problem is that the number of records are around 1.5 million. The script always runs for about 14 hours every time and gives this error : mysql_query unable to save result set in xx on line xxx. and phpmyadmin gives this error #2008 out of memeory
Here is my php code
mysql_query("SET SQL_BIG_TABLES=1");
$res = mysql_query("SELECT company_name, country, id FROM proj")
or die (mysql_error());
while ($row = mysql_fetch_array($res, MYSQL_NUM)) {
$res1 = mysql_query("SELECT company_name, id FROM proj WHERE country='$row[1]'"+
"AND id<>'$row[2]'") or die ("here".mysql_error().mysql_errno());
while ($row1 = mysql_fetch_array($res1, MYSQL_NUM)) {
//My calculations here
}
}
Ok. Your query is incredibly inefficient. You say in a comment that there's 1.5 million rows.
Outside query creates a result set with all 1.5 million rows
Inside query creates a new result set with all 1.5 million rows, EXCEPT the row that has the same of the row you're looping on. So basically you're doing 1.5 million * (1.5 million - 1) rows =
2,249,998,500,000 = 2.25 trillion rows
In other words, not only incredibly inefficient - it's absolutely ludicrous. Given you seem to want to fetch only rows by country, why not do something like:
$sql1 = "SELECT DISTINCT country FROM proj";
$res1 = mysql_query($sql1) or die(mysql_error());
while($row1 = mysql_fetch_associ($res1)) {
$country = $row1['country'];
$escaped_country = mysql_real_escape_string($country);
$sql2 = "SELECT company_name, id FROM proj WHERE country='$country'";
$res2 = mysql_query($sql2) or die(mysql_error());
while ($row2 = mysql_fetch_assoc($res2)) {
... calculations ...
}
}
This'd fetch only 1.5 million + # of country records from the database, which is far far far less than the 2.3 trillion your version has.