Insert query inside a loop with sleep() function not working - php

I have a while loop with a sleep() function given below :
$employee = mysqli_query( $conn , "SELECT emp_id,emp_name FROM employee
WHERE DATE(datetime) = '$date' " );
if(mysqli_num_rows($employee) > 0){
while ($row = mysqli_fetch_array($employee)) {
$emp_id = $row['emp_id'];
$emp_name = $row['emp_name'];
$number = mysqli_query( $conn ,"SELECT phone_number FROM emp_phone_number
WHERE emp_id = '$emp_id' ");
if(mysqli_num_rows($number) > 0){
while ($row2 = mysqli_fetch_array($number)) {
sleep(2);
}
}
mysqli_query($conn , " INSERT INTO `emails`(`emp_id`, `email`) VALUES ('$emp_id','hello') ");
}
}
The Insert query is working fine without the sleep() function. But when I enable the sleep() function it does not working. Please suggest me the reason.

Where do you open Database connection using mysqli_connect() ? It may be due to Mysql connection timeout as you have sleep of every 2 second. Try using mysqli_connect() before the mysqli_query("Insert Query"); it will work.

The PHP sleep function takes a int argument which is seconds the execution should sleep.
You choose to sleep 2 seconds for each number of each employee.
I would think that the reason your code don't "work" is cause your execution time is so long due to the sleep call that you never see it finish.
Honestly, I cant see why you would ever want to use the sleep function in this case, and it looks quite strange that you just want to sleep a few seconds if a employee have a number or more...

Several people have suggested timeout errors. That seems likely. I would try catching any exceptions to find out what is really happening
$employee = mysqli_query( $conn , "SELECT emp_id,emp_name FROM employee
WHERE DATE(datetime) = '$date' " );
try{
if(mysqli_num_rows($employee) > 0){
while ($row = mysqli_fetch_array($employee)) {
$emp_id = $row['emp_id'];
$emp_name = $row['emp_name'];
$number = mysqli_query( $conn ,"SELECT phone_number FROM emp_phone_number
WHERE emp_id = '$emp_id' ");
if(mysqli_num_rows($number) > 0){
while ($row2 = mysqli_fetch_array($number)) {
sleep(2);
}
}
mysqli_query($conn , " INSERT INTO `emails`(`emp_id`, `email`) VALUES ('$emp_id','hello') ");
}
}
}
catch(\Exception $e){
die($e->getMessage());
}

Related

Search a database to update the results

I am taking a users input and storing it in a database, however I want to be able to update the records if a user adds more information. So I want to search the database find the server with the same name and update the the last downtime and the number of downtimes.
$connect = mysqli_connect("localhost", "Username", "Password","Test_downtime");
if (!$connect)
{
die("Connection failed: " . mysqli_connect_error());
}else
{
echo "Connected successfully\n";
}
$servername = $_GET["server_name"];
$downtime = $_GET["downtime"];
$time_now = time();
$result = mysqli_query($connect, "SELECT COUNT(*) FROM `Test_downtime`.`Downtime` WHERE `Server_Name` = '$servername'");
$row = mysqli_fetch_array($result);
// If no downtime have been reported before
if ($row[0] == 0){
$sql = mysqli_query($connect, "INSERT INTO `Test_downtime`.`Downtime` (ID, Server_name, First_downtime, Last_downtime, Num_of_downtime,Total_downtime) VALUES (NULL, '$servername', '$time_now','$time_now',1,'$downtime'); ");
if ($sql==true) {
echo $servername . " has has its first downtime recorded\n";
}
}
//If users is already in the database
else{
$numdowntime = ($row["Num_of_downtime"] + 1);
$id = ($row["ID"]);
$sqlupdate = "UPDATE `Test_downtime`.`Downtime` SET `Num_of_downtime` = $numdowntime, `Last_downtime` = now() WHERE `Server_Name` = '$servername'";
if ($sqlupdate == TRUE) {
echo "Oh No! " . $servername . " has had ". $numdowntime ." of downtimes" ;
}
}
?>
The program works fine if the server is not already in the database, the problems arise if the server is already in the database. I get the message saying it has been updated yet nothing happens to the database. How do i make it so it search and updates the records for the searched item.
So nothing append since you do not execute the sql statement ^^
Take a look here :
$sqlupdate = "UPDATE `Test_downtime`.`Downtime` SET `Num_of_downtime` = $numdowntime, `Last_downtime` = now() WHERE `Server_Name` = '$servername'";
You need to use :
$sql = mysqli_query($connect, $sqlupdate);
Just after it in order to execute it.
Or at least change it to
$sqlupdate = mysqli_query($connect, "UPDATE `Test_downtime`.`Downtime` SET `Num_of_downtime` = $numdowntime, `Last_downtime` = now() WHERE `Server_Name` = '$servername'" );
Btw there is other problem but here is the main one [check out the other answer in order to found another one ]
you are fetching the result as indexed array
mysqli_fetch_array($result);
and here you are accessing results as associative array
$numdowntime = ($row["Num_of_downtime"] + 1);
change your query to
mysqli_fetch_assoc($result);
use
mysqli_num_rows($result);
to checking if you have any data
change
if ($row[0] == 0){}
to
if(mysqli_num_rows($result) ==0){}
A good approach for increasing a count in a column is using SQL to increase that.
$sqlupdate = mysqli_query($connect, "UPDATE `Test_downtime`.`Downtime` SET `Num_of_downtime` = (`Num_of_downtime` + 1), `Last_downtime` = now() WHERE `Server_Name` = '$servername'" );
This way you can skip your $numdowntime calculation, and the result is more accurate.
In your current setup, two users may fire the event at the same time, they both retrieve the same number from the database (ie. 9), both increasing it with one (ie. 10), and writing the same number in the database.
Making your count one short of the actual count.
SQL takes care of this for you by locking rows, and you are left with a more accurate result using less logic :)
You miss the mysqli_query() function, which actually queries the database.
$sqlupdate = mysqli_query("
UPDATE `Test_downtime`.`Downtime`
SET `Num_of_downtime` = $numdowntime, `Last_downtime` = now()
WHERE `Server_Name` = '$servername'"
);

Booking Availability

I have a database field which are
Appt_Datetime (which is call as DateTime in my table)
Svc_ID (which i call ApptType in my table)
I wanted the system to let the customer know that the datetime for the appt type is not available once someone else has book that slot.I have done a lot of research and trying out different codes but to no avail. I've seen answers on stackoverflow that uses PDO but im not so clear about it hence i'd like something to do with mysql. I have been stuck at with this at least few weeks now. Help
This is my call func:
$datetime = $_POST['DateTime'];
$appt = $_POST['ApptType'];
This is the query i last tried out but still is not working:
//Define query
$vquery = "SELECT * FROM Appointment where Appt_DateTime='$datetime' && Svc_ID='$appt'";
//Run Query
$result = mysql_query($query, $conn);
$row = mysql_fetch_assoc($result);
if($row==1)
{
echo "Date in not available";
}
else if($row==0)
{
$query = "INSERT INTO Appointment (Client_ID,Svc_ID,Appt_DateTime)
VALUES ('$_POST[ClientID]','$_POST[ApptType]','".date('Y-m-d H:i:s', strtotime($_POST[DateTime]))."')";
mysql_query($query,$conn);
}
Hint:
change this to $result = mysql_query($query, $conn); to $result = mysql_query($vquery, $conn);
at the time you are using $conn you do not have $query it is $vquery:
$result = mysql_query($vquery, $conn);
And as suggested above in comments better use mysqli or PDO.
you can try this condition..
//Define query
$vquery = "SELECT * FROM Appointment where Appt_DateTime='$datetime' && Svc_ID='$appt'";
//Run Query
if($result = mysql_query($vquery, $conn)){
//$row = mysql_fetch_assoc($result);
if(mysql_num_row($result)>0)
{
echo "Date in not available";
}
else
{
/* $query = "INSERT INTO Appointment (Client_ID,Svc_ID,Appt_DateTime)
VALUES ('$_POST[ClientID]','$_POST[ApptType]','".date('Y-m-d H:i:s', strtotime($_POST[DateTime]))."')";
mysql_query($query,$conn); */
echo "insert";
}
}else{
echo mysql_error();
}

PHP works first time then fails

Basically what this does is makes it so after the user presses a button, they have to wait 2 minutes to press it again. When you press it the first time, it works, then if you press it again before 2 minutes, it says "please wait 2 minutes." but after 2 minutes, you can press it as many times as you like without the error, not what I want. Here is the code
<?php
if('sub') {
$client = $_SERVER['REMOTE_ADDR'];
$username="user";
$password="pass";
$database="db";
mysql_connect(localhost,$username,$password);
$time = strtotime("2 minutes");
$now = strtotime("now");
#mysql_select_db($database) or die( "Unable to select database");
$query = "SELECT Time FROM log WHERE IP='$client'";
$result= mysql_query($query);
$num=mysql_num_rows($result);
while($rows=mysql_fetch_array($result)){
$timestamp = $rows['Time'];
}
echo n;
echo $now;
echo t;
echo $timestamp;
if($now < $timestamp)
{
echo "<center><h2 style=\"color:red\" class=\"texts\" id=\"homeLink\">Please wait 2 minutes.</h2></center>";
}
else{
//some other code
$query1 = "INSERT INTO log VALUES ('$client','$time','$username')";
$query2 = "UPDATE `log` SET `Time`='$time' SET `Username`='$username' WHERE `IP`='$client'";
if($num == 0)
{
mysql_query($query1);
}
else
{
mysql_query($query2);
}
mysql_close();
}
?>
As you can see, if there is no row for the IP of the user, it makes a new one, if there is it will update it. After the first time, it no longer works. Hope someone can help. Thanks!
Your update statement is a bit off, so the update fails;
UPDATE `log` SET `Time`='$time' SET `Username`='$username' WHERE `IP`='$client'"
You should only use SET once, like this;
UPDATE `log` SET `Time`='$time', `Username`='$username' WHERE `IP`='$client'"
I'm pretty sure your database does not contain entries you think it contains. Can you check it (IPs and stuff on after button press)?

Having trouble adding a 24 hour voting system?

There is a script that triggers the code below
I want to disallow executing the script more than once per 24 hours.
I wanted this script to store the last visit time in a table against the user id in a database, then do a time calculation and back them out until the 24 hour expiry time.
Can someone explain how to do this? It would be greatly appreciated if someone could help me with this?
<?php
//Input correct values into this section
$dbhost = '888888';
$dbuser = '888888';
$dbpass = '888888';
$dbname = '888888';
$dbtable = 'redeem';
$dbtable2 = 'playersthatvoted';
//------------------------------------
$input = 'diamond 12';
$player = $_POST['Player'];
$time = time();
if(!isset($_COOKIE['24Hourvote'])){
//---- This is the connection
$conn = mysql_connect ($dbhost, $dbuser, $dbpass) or die ('Error: ' . mysql_error());
mysql_select_db($dbname);
$query1 = "INSERT INTO `".$dbname."`.`".$dbtable."` (`player`, `item`) VALUES ('".$player."', '".$input."')";
$query2 = "INSERT INTO `".$dbname."`.`".$dbtable2."` (`player`, `time`) VALUES ('".$player."', '".$time."')";
mysql_query($query1);
mysql_query($query2);
$query= 'SELECT `player` FROM `playersthatvoted` ASC LIMIT 0, 10 ';
$result = mysql_query($query);
mysql_close($conn);
echo 'Done! Type /redeem in-game to get your diamonds.';
$ip=#$REMOTE_ADDR;
setcookie ("24Hourvote",$ip,time()+86400,'/',true,…
} else {
echo 'You have already voted today! Come back later...'; }
?>
EDIT: and could I make it so that it displays the time left until the user can vote again?
To me it looks like you already know what you have to do:
I wanted this script to store the last visit time in a table
against the user id in a database.Then do a time calculation and
back them out until the 24 hour expiry time.
So:
Forget about the cookie. It is stored on client side and can be manipulated.
Before count the vote check the [lastvisit] field of the current user.
If not set count the vote and set the [lastvisit] field in your table to the current date.
If set calculate the time span between now and the last vote. If bigger than 24 hours, count the vote and set the [lastvisit] field in your table to the current date.
Be aware of:
Manipulated parameters: $_POST['Player'];
SQL injections: VALUES ('".$player."', '".$input."')
If you have problems with one of these tasks then ask about the specific problem.
<?php
//Input correct values into this section
$dbhost = '888888';
$dbuser = '888888';
$dbpass = '888888';
$dbname = '888888';
$dbtable = 'redeem';
$dbtable2 = 'playersthatvoted';
//------------------------------------
$input = 'diamond 12';
$time = time();
if(!isset($_COOKIE['24Hourvote'])){
$ip = $_SERVER['REMOTE_ADDR'];
//---- This is the connection
$conn = mysql_connect ($dbhost, $dbuser, $dbpass) or die ('Error: ' . mysql_error());
mysql_select_db($dbname);
// Escape all user entered data always
$player = mysql_real_escape_string($_POST['Player']);
// Select time for this player if available
$query = "SELECT time FROM playersthatvoted WHERE player = '$player' ORDER BY time DESC LIMIT 0, 1";
$result = mysql_query($query);
if(mysql_num_rows($result) != 0)
{
$row = mysql_fetch_row($result);
$last_visit = $row[0];
$vote_allowed_time = $last_visit + 86400;
// Allowed to vote
if($time > $vote_allowed_time)
{
// Do whatever else you need to here ...
setcookie ("24Hourvote",$ip,time()+86400,'/');
}
else
{
echo 'This player has already voted today! Come back later...';
}
}
else
{
$query1 = "INSERT INTO `".$dbname."`.`".$dbtable."` (`player`, `item`) VALUES ('".$player."', '".$input."')";
$query2 = "INSERT INTO `".$dbname."`.`".$dbtable2."` (`player`, `time`) VALUES ('".$player."', '".$time."')";
mysql_query($query1);
mysql_query($query2);
$query= 'SELECT `player` FROM `playersthatvoted` ASC LIMIT 0, 10 ';
$result = mysql_query($query);
mysql_close($conn);
echo 'Done! Type /redeem in-game to get your diamonds.';
setcookie ("24Hourvote",$ip,time()+86400,'/');
}
} else {
echo 'You have already voted today! Come back later...'; }
?>
Note: Never trust the user input, always validate and escape the data.
Changed:
$player = $_POST['Player'];
to:
$player = mysql_real_escape_string($_POST['Player']);
Added:
// Select time for this player if available
$query = "SELECT time FROM playersthatvoted WHERE player = '$player' ORDER BY time DESC LIMIT 0, 1";
$result = mysql_query($query);
if($result)
{
$row = mysql_fetch_row($result);
$last_visit = $row[0];
$vote_allowed_time = $last_visit + 86400;
// Allowed to vote
if($time > $vote_allowed_time)
{
// Do whatever else you need to here ...
setcookie ("24Hourvote",$ip,time()+86400,'/');
}
else
{
echo 'This player has already voted today! Come back later...';
}
}
else
{
...
}
UPDATE
I would like to highlight the fact that as it stands anyone can enter the player name and try to vote for it and that does not necessarily mean the same user who clicks the vote button.
Additionally the IP address is not being used for any purposes, it may be an idea to use this for further permission/security checks.

Prevent two calls to the same script from selecting the same mysql row

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
}
}

Categories