I stuck in some code here E.G:
Database table :
IMG_ID|IMG_SRC|EXPIRES|ACTION
------------------------------
4 | st.jpg |12546564| temp
So i try to delete the image from DB and from directory path so far i got this :
function removeTempPic(){
$uploadsDirectory1 = $_SERVER['DOCUMENT_ROOT'].'test/uploads/temp/';
//remove after 10 minute if unused
$timeout = time()-TEMPIC_TIMEOUT*60;
$q = "SELECT * FROM picsmanager WHERE expires < $timeout AND action=temp";
mysql_query($q, $this->connection);
foreach ($row = mysql_fetch_array($q)) {
$q = "delete * from picsmanager where=??"
//#unlink($uploadsDirectory1.$uploadFilename);
}
}
So what i try to do is select all from database table , and where timeout expire in some row delete each image from db and from directory
But this wont work because i dont know how to make it properly , Thanks.
you have multiple errors, in PHP and SQL
// enclose the string "temp" in single quotes
$q = "SELECT * FROM picsmanager WHERE expires < $timeout AND action='temp'";
$result = mysql_query($q, $this->connection);
// you need the result, not $q again
while($row = mysql_fetch_array($result)){
// run a new query to delete the extracted image
mysql_query("delete from picsmanager where IMG_ID=" . $row['IMG_ID'] . " LIMIT 1", $this->connection);
// delete the corresponding file
unlink($uploadsDirectory1.$row['IMG_SRC']);
}
Also, don't use the mysql_* functions anymore, they are becoming deprecated and will be removed from PHP in the future. Your code will stop working then. Learn how to use mysqli_* or PDO objects.
function removeTempPic(){
$uploadsDirectory1 = $_SERVER['DOCUMENT_ROOT'].'test/uploads/temp/';
//remove after 10 minute if unused
$timeout = time()-TEMPIC_TIMEOUT*60;
$q = "SELECT * FROM picsmanager WHERE expires < $timeout AND action='temp'";
mysql_query($q, $this->connection);
foreach($row = mysql_fetch_array($q)){
$q = sprintf("delete * from picsmanager where IMG_ID = %d", (int)$row['IMG_ID']);
//#unlink($uploadsDirectory1.$uploadFilename);
}
}
Related
I am trying to display last visit of a user in my page.
The commands seems ok, but it doesn't work.
I have tried everything.
DATABASE SELECTION-OK
TABLE SELECTION-OK
if($result)- EXECUTES
but the UPDATE and the details I can not fetch from database.
Here's the code:
$conn = mysqli_connect("localhost","root","","counter");
$qry = "SELECT * FROM nodupes WHERE ids_hash = 'ids_hash'";
$result = mysqli_query($conn,$qry);
if($result)
{
$data = mysqli_fetch_assoc($result);
$lastvisit = $data["lastvisit"];
$timex = time() - $lastvisit;
}
$curr_time = time();
$qry2 = "update nodupes set lastvisit='$curr_time' WHERE ids_hash='ids_hash'";
$result2 = mysqli_query($conn,$qry2);
What should I do? The lastvisit in the database always shows 0
This is what i am trying right now but no luck
$bid = $next - 2;//This subtracts 2 from the number, this number is also auto generated
$preid = $bid;
$query = "SELECT * FROM images where imageid = '$preid'";
$sql = mysqli_query($conn,$query) or die(mysqli_error($conn));
while(mysqli_num_rows($sql) !=0) {
$select_query = "SELECT * FROM images where imageid = '$preid'";
$sql = mysqli_query($conn,$select_query) or die(mysqli_error($conn));
--$preid;
}
whats suppose to happen is that if a record does not exist it subtracts 1 from preid and runs the query again with the new preid and keeps happening until a record it found but cant figure out how to do it.
I am assuming that you are constantly checking database for new values. However, on a large scale application thi is an highly inefficient way to constantly ping the database.
You have made a variable $preid but you are not using it anywhere.
This is how i would do it if i were to go according to your way
$bid = $next - 2;//This subtracts 2 from the number, this number is also auto generated
$preid = $bid;
$query = "SELECT * FROM images where imageid = '$preid'";
$sql = mysqli_query($conn,$query) or die(mysqli_error($conn));
while(mysqli_num_rows($sql) !=0 || !$preid) { //notice here i added the condition for preid.
$select_query = "SELECT * FROM images where imageid = '$preid'";
$sql = mysqli_query($conn,$select_query) or die(mysqli_error($conn));
--$preid;
}
now what happens is that the loop will run as long as either of the two condition stays true ie either a row is returned from the database or it will keep searching until preid is not 0.
If you want to test for an empty set, your while should run while mysqli_num_rows == 0
while(mysqli_num_rows($sql) == 0) {
$select_query = "SELECT * FROM images where imageid = '$preid'";
$sql = mysqli_query($conn,$select_query) or die(mysqli_error($conn));
$preid--;
}
As #DarkBee has mentionend in his comment, this code is highly vulnerable for an infinite loop which will take down your script, as soon as there are no entries for anything.
I'm writing a very simple seating plan arranger for my sister. All it is, is a database with a list of people attending and each has a table number assigned ($tano)
My PHP is as follows:
$con = mysql_connect('localhost', $dbuser, $dbpass) or die(mysql_error());
$db = mysql_select_db($dbname, $con) or die(mysql_error());
// Get current table no
$tableno = $_GET["t"];
// Current table -> array
$t = array();
$i = 0;
$result = mysql_query('SELECT * FROM plan WHERE tano = $tableno ORDER BY fname');
while($row = mysql_fetch_array($result)) {
$t[$i] = $row;
$i++;
}
// Get other tables (Seats Remaining)
for ($i = 1; $i <= 40; $i++) {
$result = mysql_query("SELECT * FROM plan WHERE 'tano' = $i");
$seatsremaining = 10-mysql_num_rows($result);
if ($seatsremaining == 0) {$d[$i] = "Table ".$i." (No Seats Remaining)";}
else if ($seatsremaining == 1) {$d[$i] = "Table ".$i." (1 Seat Remaining)";}
else if ($seatsremaining >= 2) {$d[$i] = "Table ".$i." (".$seatsremaining." Seats Remaining)";}
}
?>
You can see the rest of the HTML code on www.greenbottleblue.com
The array is not populated and there's an annoying SQL error:
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in /home/greenbot/public_html/index.php on line 18
The table structure is:
In your first query, you are missing quotes around your value:
$result = mysql_query('SELECT * FROM plan WHERE tano = $tableno ORDER BY fname');
This should be:
$result = mysql_query("SELECT * FROM plan WHERE tano = '$tableno' ORDER BY fname");
In your second query, you are using quotes instead of backticks around the column name:
$result = mysql_query("SELECT * FROM plan WHERE 'tano' = $i");
This should be:
$result = mysql_query("SELECT * FROM plan WHERE `tano` = $i");
You should note that your code assumes that the query completed successfully instead of checking. For debugging purposes, you can add:
... or die(mysql_error());
to the end of each of your mysql_query(...) statements to get details about the attempted queries. You should develop a logging strategy for such errors in production code.
Additionally, be aware that using unfiltered user input $tableno = $_GET["t"]; opens the door for SQL injection attacks. Consider updating your code to use parameterized PDO queries, or at least filter your incoming data.
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'm trying to get a pick from my DB that would last for a day (daily pick). I use the following code:
$query = 'SELECT * FROM table ORDER BY rand() LIMIT 1
But as you can see it only gives me a random pick from the table, and every time I refresh the page it gets me a new random pick. How can I make the pick to last for a whole day?
Thanks in advance <3
I'm trying this:
$query = "SELECT * FROM table ORDER BY rand(" . date("Ymd") . ") LIMIT 1";
But I get the following error: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource. This is the part that gets broken:
$results = mysql_query($query);
while($line = mysql_fetch_assoc($results))
So... it should look like this, right? (I mean, choosing the daily random pick?)
$dailyPick = 'SELECT * FROM table ORDER BY rand() LIMIT 1';
$cacheKey = 'dailyPick'. date('dmY');
if($cache->has($cacheKey)) {
$dailyPick = $cache->get($cacheKey);
} else {
// hit database
$dailyPick = $cache->save($cacheKey);
}
I'm trying this now:
$dailyPick = 'SELECT * FROM table ORDER BY rand() LIMIT 1';
$cacheKey = 'dailyPick'. date('dmY');
if($cache->has($cacheKey)) {
$dailyPick = $cache->get($cacheKey);
} else {
// hit database
$dailyPick = $cache->save($cacheKey);
}
However, it gets me a mistake that I'm using the 'has' function on a non-object.
If you set the SEED for the rand to an integer value that changes daily, that would solve your problem
$query = "SELECT * FROM table ORDER BY rand(" . date("Ymd") . ") LIMIT 1";
Would do the trick.
A sane means of doing this would be to automatically generate the pick of the day content via a cron job that was setup to run once a day.
As such, the cron job would execute the SQL you provided and store the appropriate content in a flat file/database table, etc. (or perhaps even just store the choosen id in another table for future lookup purposes).
You can try something like this:
$total = 'SELECT COUNT(*) FROM table;';
$query = 'SELECT * FROM table ORDER BY id ASC LIMIT 1 OFFSET ' . (date('Ymd') % $total) . ';';
I think you'll need to update the random picked record with "today" field = 1..
Something like this:
// ------------
// Run this 3 commands once a day
// Reset all records
mysql_query("UPDATE `table` SET `today` = 0");
// Pick one
$sql = mysql_query("SELECT `id` FROM `table` ORDER BY RAND() LIMIT 1");
$id = mysql_result($sql, 0, 'id');
// Update the record
mysql_query("UPDATE `table` SET `today` = 1 WHERE `id` = {$id}");
// ------------
// Now you can find again your "random found record":
$query = mysql_query("SELECT * FROM `table` WHERE `today` = 1");