Search code examples
phpmysqlsqlsql-insertsql-delete

PHP and mySQL, working with current date?


PHP and mySQL question I hope you could help me out with. I have an update database option (by clicking a button, it runs the update.php file), now this update.php is responsible for trying to separate my PASSENGER table.

At the moment, I have one massive PASSENGER table, where if there trip with the business happens today (it is a travel booking firm), then they are in the CUSTOMER table, but I want any archived customers (e.g. anyone that travelled from yesterday backwards, to be put into the ARCHIVED_CUSTOMER table.

Now at the moment, I have a small PHP script that is adding to the ARCHIVED_PASSENGER table using the information from the current PASSENGER table, but only where the parameter is the PASSENGER ID.

I am quite comfortable with the DELETE FROM PASSENGER part of the script, but was wondering if anyone knew the code that would allow me to collect and move mass information from the database, where the DATE OF TRAVEL is yesterday onwards etc.. it is done through the activeUntil part of the PASSENGER table.

Very stripped down PHP script, but hope I've made myself clear!

   mysql_connect("localhost", "mysql_username", "mysql_password") or die(mysql_error());
    mysql_select_db("mysql_database") or die(mysql_error());

    $query10 = ("SELECT p.surname, p.passNo, p.activeUntil FROM PASSENGER p WHERE passNo = '20120003'");

            $result = mysql_query($query10);  
            while($row = mysql_fetch_array($result))
            {

$surname =  $row['surname'];
$passNo = $row['passNo']; 

mysql_query("INSERT INTO ARCHIVED_PASSENGER (surname, passNo) VALUES ('$surname', '$passNo')  ") 
    or die(mysql_error());  

    mysql_query("DELETE FROM PASSENGER (surname, passNo) VALUES ('$surname', '$passNo')  ") 
    or die(mysql_error());  


        }

Solution

  • NOW() in MySQL gives the current timestamp. 24 hours ago is DATE_ADD(NOW(),INTERVAL -1 DAY).

    You can compare dates just like numbers: activeUntil < DATE_ADD(NOW(),INTERVAL -1 DAY) selects rows where the activeUntil was anything before 24 hours ago.

    You can combine INSERT and SELECT like so:

    INSERT INTO `archived_passenger` (columns.....) SELECT columns... FROM `passenger` WHERE ...
    

    (You can omit the first set of columns if the names of the columns in achived_passenger exactly match those in passenger, and you can use * instead of the second set of columns if you want to select all columns)

    I think that should be enough infomation to help you do what you're trying to do. Let me know if you need any additional help.