How to update data when the expiration time ends - php

I have build an apps with Codeigniter and want to make cron job and use MySQL
i have a table 'order' and have field like this
order_id | order_expired_date
001 | 2018-11-12 10:03:33
and i have table 'order_payment' like this,
order_id | op_status
001 | pending
I have many fields in these two tables but only include those that have something to do with this question
i have code from php but not in model codeigniter
$result = mysql_query('UPDATE `'order_payment'`
SET op_status='expired'
WHERE
(UNIX_TIMESTAMP( now( ) ) - `order_expired_date`));
The question is how to change the status in the order_payment table to expire when the expiration time is up?

You may use following code, you need to modify code as per your requirements..
<?php
$servername = "xyz";
$username = "xyz";
$password = "xyz";
$dbname = "xyz";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) die("Connection failed: " . $conn->connect_error);
$sql = "SELECT *,o.`order_id` as `oid` FROM `order` as o,`order_payment` as op WHERE o.`order_id`=op.`order_id` AND op.`op_status`='paid'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$today = date('Y-m-d');
$expDt = date('Y-m-d',strtotime($row['order_expired_date']));
if($today==$expDt){
$updCltSql = "UPDATE `order_payment` SET `op_status`='expired' WHERE `order_id`='".$row['oid']."'";
$conn->query($updCltSql);
}
}
}
$conn->close();
?>
We always prefer core-php file as cron-job..

After plenty of research, this is what I came up with - hope it helps. In your example, I don't think you need to put single quotes around the table name order_payment, unless that is something unique to CodeIgniter.
$orderID = mysql_query("SELECT order_id FROM order"); // Get order IDs of order table, assuming it has the same list of order IDs as the order_payment table
$order_ids = array(); // Put in array
while ($row = mysql_fetch_array($orderID)) {
$order_ids[] = $row['order_id'];
}
foreach ($order_ids as $order_id) { // Iterating through order_id's of array in order to read same index/row number from both tables
$expirationDate = mysql_query("SELECT order_expired_date FROM order WHERE order_id='$order_id'");
$expire = date('M j Y g:i A', $expirationDate); // Converting MySQL timestamp to correct format for strtotime
$today = strtotime("now");
if($today >= $expire) // If past the expiration date
mysql_query("UPDATE order_payment SET op_status='expired' WHERE order_id='$order_id'");
}

Related

trying to UPDATE SQL after one SQL

I am calculating AGE by DATE from DOB field, then I want to push it into AGE with correct age based on DOB . So As I debug The DOB calculating to AGE is works, but it cannot update AGE the code:
<?php
$servername = "localhost";
$username = "usernameexmaple";
$password = "passworking";
$dbname = "dbnameworking";
// Create connection
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id as ID, YEAR(CURRENT_TIMESTAMP) - YEAR(dob) - (RIGHT(CURRENT_TIMESTAMP, 5) < RIGHT(dob, 5)) as age
FROM regio_users";
$sql2 = ("UPDATE regio_users SET age = '$newage' WHERE id ='$newid' ");
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$newage = $row['age'];
$newid = $row['ID'];
$sql2 = ("UPDATE regio_users SET age = '$newage' WHERE id ='$newid' ");
$result2 = $conn->query($sql);
if ($result2){
echo "done"."<br>";
}
}
}
else {
echo "0 results";
}
$conn->close();
?>
It echos DONE for every ID but not updating anything at all.
You have used $result2 = $conn->query($sql); which is incorrect. You have to use $result2 = $conn->query($sql2); as $sql2 is the new query you formed.
This can be done with a single line SQL, rather than using PHP to loop through all the rows to only update the age:
UPDATE `regio_users` SET `age` = YEAR(CURRENT_TIMESTAMP) - YEAR(`dob`) - (RIGHT(CURRENT_TIMESTAMP, 5) < RIGHT(`dob`, 5));
As saty pointed, use correct variable name.
Check if autocommit is on. If not, make sure you commit the data. Check for its syntax in PHP.

The total number of mysql results not displaying properly

I am working on a total page view system and each time someone visits a page it adds the current data and their ip address. When I go to display the total number of rows on a particular day the site just displays 'Rows' without the number.
Code:
<?php
$servername = "";
$username = "";
$password = "";
$dbname = "";
$date = date("Y-m-d-h-m-s");
$ip = $_SERVER['REMOTE_ADDR'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$date = date("Y-m-d");
$result = mysqli_query("SELECT FROM page_views WHERE date = $date");
$num_rows = mysqli_num_rows($result);
echo "$num_rows Rows\n";
$conn->close();
?>
Could someone please indicate what is going wrong.
Your query is failing but you don't know it because you don't check for errors. If you did you would see a syntax error due to you omitting the * from your SELECT clause and your date not being in quotes.
Change:
$result = mysqli_query("SELECT * FROM page_views WHERE date = $date");
to:
$result = mysqli_query("SELECT * FROM page_views WHERE date = '$date'");

How to select a timestamp using date in mysql and php

I want to query if there is a particular timestamp for a day using the distinct dates that are present in a table and so far I have come up with this code
$mysqli = new mysqli('localhost', 'root', 'rolemodel', 'dashboard');
$dates = "SELECT DISTINCT DATE_FORMAT(mytimestamp, '%Y-%m-%d') FROM ".$this->table_name." ORDER BY DATE(mytimestamp) ASC;";
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$rowsdata = $mysqli->query($dates); // get number of rows
$num_rows_date = $rowsdata->num_rows;
for ($i = 0; $i<=$num_rows_date; i++) {
$current_query = "SELECT mytimestamp FROM ".$this->table_name." WHERE mytimestamp =".$rowsdata[$i]; //not sure on what to use here
}
I am confused on how to query the exact timestamp which is supposed to be the particular day along with the 00:00:00
Example 2014-06-02 00:00:00
Hope my question makes sense.
try:
//$rowsdata = $mysqli->query($dates); // get number of rows
//$num_rows_date = $rowsdata->num_rows;
//for ($i = 0; $i<=$num_rows_date; i++) {
//This is usually the way you want to do this with plain old arrays
if($result = $mysqli->query($dates)){
while($row = $result->fetch_row()){
$current_query = "SELECT mytimestamp FROM ".$this->table_name." WHERE DATE(mytimestamp) ='".$row[0] . "'";
//do something awesome here ...
}
}
See the docs for the DATE function.
BUT ... it looks like you're just querying the same table you pulled the dates from in the first place, so you're guaranteed to find timestamps with those dates. Not sure what you're ultimately after, but you may be able to do it with a single query.

Checking MySQL's DATETIME in PHP

I lack some experience with PHP/MySQL environment. I have a MySQL table called MyTable. In it I have a field called RowTime of type DATETIME NOT NULL. After selecting the row in PHP, I want to check whether RowTime is older or younger than 3 days.
Given all the different types of time types, can someone please help completing the following code (I'm deliberately omitting various error handling):
$dblink = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
$dbquery = "SELECT RowTime FROM MyTable WHERE Id='" . $myId . "'";
$result = mysqli_query($dblink, $dbquery);
$numrows = mysqli_num_rows($result);
// ... Verify $numrows == 1 ...
$myRow = mysqli_fetch_assoc($result);
$rowTime = $myRow['RowTime'];
// NEED HELP HERE to check whether $rowTime is older or younger than 3 days
mysqli_free_result($result);
You can use special SQL operator to check that your date older than 3 days:
$dblink = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
$dbquery = "SELECT RowTime, IF(RowTime + INTERVAL 3 DAYS > now(), true, false) as isYounger FROM MyTable WHERE Id='" . $myId . "'";
$result = mysqli_query($dblink, $dbquery);
$numrows = mysqli_num_rows($result);
// ... Verify $numrows == 1 ...
$myRow = mysqli_fetch_assoc($result);
$rowTime = $myRow['RowTime'];
if($myRow['isYounger']) {
//record is younger
} else {
//record is older
}
mysqli_free_result($result);
You can use the following query:
SELECT RowTime,TIMEDIFF(NOW(),RowTime)>"72:00:00" AS "Old" FROM MyTable ;
This will introduce column "Old" which will be 1 if RowTime is older than 3 days. Otherwise it'll be 0. Please note that this doesn't take the timezone into account.

I need to output my Access table to a website using PHP

Alright, I have no problem outputting multiple lines of data out of the database, I just have no idea how to get it out in the format I want.
Here's my basic issue.
<tr>
<?php
//make connection to database, bail if no connection
$connection = odbc_pconnect('sitedata','','');
if (!$connection) { exit("Connection Failed: " . $connection); }
//retrieve relevant data
$Date = "SELECT EntryDate AS DT FROM TimeSheet WHERE EmployeeID = 'AA01'";
$rs = odbc_exec($connection, $Date);
//output data
while(odbc_fetch_row($rs)) {
$Line1 = odbc_result($rs, 'DT');
printf("<td><center>%s</center></td>", $Line1);
}
?>
</tr>
What this will do is output a one row table, with each new date creating a new column.
Now then, this is sort of useless to me as these need to be output into a single column, where each new datavalue is the beginning of a row. After this, I need to expand the table width wise, adding new data values such as:
$Time = "SELECT TotalTime as EN FROM TimeSheet WHERE EmployeeID = 'AA01'";
$JobName = "SELECT JobName as JN FROM TimeSheet WHERE EmployeeID = 'AA01'";
Where Time is it's own column, JobName is it's own column, etc.
How exactly do I do this? There obviously must be a way, I'm just new at this. Any help is greatly, greatly appreciated!
You need to get the fields in one SQL statement...
SELECT EntryDate AS DT, TotalTime as EN, JobName as JN
FROM TimeSheet WHERE EmployeeID = 'AA01';
With that you can do exactly what you are doing now except build a full row instead of columns.
<?php
//make connection to database, bail if no connection
$connection = odbc_pconnect('sitedata','','');
if (!$connection) { exit("Connection Failed: " . $connection); }
//retrieve relevant data
$Date = "SELECT EntryDate AS DT, TotalTime as EN, JobName as JN FROM TimeSheet WHERE EmployeeID = 'AA01';";
$rs = odbc_exec($connection, $Date);
//output data
while(odbc_fetch_row($rs)) {
$DT = odbc_result($rs, 'DT');
$EN = odbc_result($rs, 'EN');
$JN = odbc_result($rs, 'JN');
printf("<tr><td>%s</td><td>%s</td><td>%s</td></tr>", $DT, $EN, $JN);
}
?>

Categories