I want to know how can I work with dates in MySQL and PHP. I want to know how many days remain, i want to know how many day is defference(distance) between nowTime and createTime ?
<?php
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
////ISSET
if (isset($_POST['projectId'])) {
$projectId = $_POST['projectId'];
$result = mysql_query("SELECT *FROM projects WHERE projectId='$projectId'") ;
if (mysql_num_rows($result)>0) {
$result = mysql_fetch_array($result);
$response["title"]=$result["title"];
$response["exp"]=$result["exp"];
$response["userIdKarmand"]=$result["userIdKarmand"];
$response["userIdKarfarma"]=$result["userIdKarfarma"];
$response["cost"]=$result["cost"];
$response["zemanat"]=$result["zemanat"];
$response["time"]=$result["time"];
$response["createTime"]=$result["createTime"];
$response["type"]=$result["type"];
$response["nowTime"]=DATE("y-m-d");
$response["remainTime"]=DATE("y-m-d")- strtotime($response["createTime"])+$response["time"];
echo json_encode($response);
}
else {
}
}
else {
}
?>
It's not working. What can I do? I want compare createtime and nowtime and find out how many days I have time?
strtotime converts formatted string date format to timestamp. You can't substract timestamp data from string data. You have to first convert $response["remainTime"] to timestamp using strtotime() and then substract strtotime($response["createTime"]) from this value.
The best way to go through a MySQL result would be to loop through the fetch_assoc() function.
$result = mysql_query("SELECT * FROM projects WHERE projectId = '$projectId'");
// while() through an associative array from the MySQL object
while($result =& $result->fetch_assoc()) {
$response["title"] = $result["title"];
$response["exp"] = $result["exp"];
$response["userIdKarmand"] = $result["userIdKarmand"];
$response["userIdKarfarma"] = $result["userIdKarfarma"];
$response["cost"] = $result["cost"];
$response["zemanat"] = $result["zemanat"];
$response["time"] = $result["time"];
$response["createTime"] = $result["createTime"];
$response["type"] = $result["type"];
$response["nowTime"] = DATE("Y-m-d H:i:s"); // this is how you would need to format dates to work with MySQL
$remainTime = (strtotime($response['nowTime']) - strtotime($response['createTime'])); // this would return how many seconds have passed since $response['createTime'] until now
$response["remainTime"] = $remainTime;
}
echo json_encode($response);
This would allow you to have how many seconds since $response['createTime'] held in the $remainTime variable.
Related
Hello I want to update MySQL table automatic at set time like i want to update table at 5:30 i have some values to update in my database at set time automatic. in PHP
$date = date('H:i:s');
if($date == "11:26:00") // 17:30:00 is equal to 5:30 but in 24 system
{
$sql1 = "SELECT * FROM No where id='1'";
$result1 = mysqli_query($mysqli,$sql1) or die(mysqli_error());
while($row= mysqli_fetch_assoc($result1))
{
$Foo= $row['foo'];
}
$sql2 = "UPDATE No SET id='2',foo='$foo' where id='2'";
$result2 = mysqli_query($mysqli,$sql2) or die(mysqli_error());
}
Just lie what Ashish said you can use CRON , and if you want you maybe can use this , i did not use before , try it . This code will works once ,so you have to find away to make loop cause the time will change every sec .
Note : Check the second code .
<?php
// Database connect
$date = date('H:i:s'); // Set the time to hours and minutes and seconds format
// you can echo $date to check how it looks but it will be something like this : 07:21:48
if($date == "17:30:00") // 17:30:00 is equal to 5:30 but in 24 system
{
// You can type your code here .
}
?>
Second Code :
<?php
// Remember to connect to your database
$date1 = date_create("00:00");
$date2 = date_create("23:59");
while($date1<=$date2)
{
date_add($date1,date_interval_create_from_date_string("1 sec"));
$a = date_format($date1,"H-i-s");
if($a =='17:30:00')
{
$sql1 = "SELECT * FROM No where id='1'";
$result1 = mysqli_query($mysqli,$sql1) or die(mysqli_error());
$row= mysqli_fetch_assoc($result1)
{
$Foo= $row['foo'];
$sql2 = "UPDATE No SET id='2',foo='$foo' where id='2'";
$result2 = mysqli_query($mysqli,$sql2) or die(mysqli_error());
}
die;
}
else
{
// you can type anything here , you can end the process by typing die; or anything you want
}
}
?>
You can check this and see how you can loop throw date in php :
I have 2 dates in PHP, how can I run a foreach loop to go through all of those days?
This can help you understand the time and date system and how to change the format for the date in php : How to get the current date and time in PHP?
I have php code with two queries. One is in an Oracle database, with the result being about 100 rows of data (within the data there are SKU numbers). The other is in a mysql database with about 30 rows of data (with the data there are also SKU numbers).
I need to compare each SKU in the first query to the second query, line by line. If the SKU in the first query also appears in the second query, then I need it to echo the SKU.
All SKUs in the second query are in the first query, so I would expect the result to echo all 30 SKUs, but it does not. Depending on how I change the syntax, it echos 17 rows, 100 rows, or no rows at all.
It's worth noting that both queries work fine. The Oracle query is insanely long and has a lot of sub-queries in it, so I will not include that full query below. The Oracle query returns the results perfectly in SQL Developer, and the MySQL query returns the results perfectly in HeidiSQL. Both queries have been tested and echoed as tables in other php files to make sure that they were working fine.
Below is what the php file that I am trying to fix looks like so far;
<?php
$conn = oci_connect($user, $pswd, $hst);
$sql = oci_parse($conn,"[Really long Oracle Query]");
while ($row = oci_fetch_assoc($sql))
{
$sku = $row['SKU'];
$con = mysql_connect("[database host]", "[database user]", "[database password]");
mysql_select_db("[database_name]");
$sqls = "SELECT * FROM [table_name] WHERE [this_date_column] BETWEEN
DATE_SUB(NOW(), INTERVAL 14 DAY) AND NOW()";
$result = mysql_query($sqls);
$mailer = NULL;
while($rows = mysql_fetch_assoc($result))
{
$m_sku = $rows['sku'];
if ($m_sku == $sku)
{
$mailer == 'false';
}
}
if ($mailer == 'false')
{
echo $m_sku;
echo "<br>";
}
}
?>
Again; there are only 30 SKUs in the MySQL query, but over 100 SKUs in the Oracle query. All SKUs in the MySQL query are definitely in the Oracle query.
Anyone see what I am doing wrong?
Thanks in advance,
-Anthony
You have basic sintacsis errors:
= is used to assign values
== compares 2 variables (not counsidering there type *)
=== compares 2 variables including there types.
your code should look something like this:
while($rows = mysql_fetch_assoc($result))
{
$m_sku = $rows['sku'];
if ($m_sku == $sku)
{
$mailer = false; // == is for comparison, = is for assign
}
}
if ($mailer === false)
{
echo $m_sku;
echo "<br>";
}
if($member == 'false'){...}
when 'false' is compared with == to a falsefull value (0, null, false, array(), '') .. it will NOT be mach it as it is parsed as a "not empty string" so it is not falsefull .
Here is your code with the MySQL connect moved outside the loop and the == assignment fixed.
<?php
//Connect to databases
$oracle = oci_connect($user, $pswd, $hst);
$mysql = mysql_connect("[database host]", "[database user]", "[database password]");
mysql_select_db("[database_name]");
//Get rows from Oracle
$oracle_result = oci_parse($oracle, "[Really long Oracle Query]");
$oracle_rows = array();
while ($row = oci_fetch_assoc($oracle_result)) $oracle_rows[] = $row;
//Get rows from MySQL
$mysql_sql = "SELECT * FROM [database_name] WHERE this_date_column BETWEEN
DATE_SUB(NOW(), INTERVAL 14 DAY) AND NOW()";
$mysql_result = mysql_query($mysql_sql);
$mysql_rows = array();
while ($row = mysql_fetch_assoc($mysql_result)) $mysql_rows[] = $row;
foreach ($oracle_rows as $oracle_row) {
$oracle_sku = $oracle_row['SKU'];
foreach ($mysql_rows as $mysql_row) {
$mysql_sku = $mysql_row['sku'];
$mailer = null;
if ($mysql_sku == $oracle_sku) {
$mailer = false;
echo $mysql_sku . "<br>";
}
}
}
I tried to search for something similar in the web but no results.
What I am trying to do is simply taking the results from the DATABASE and then run some functions for EACH result.
We have two kinds of functions.
The first function is when the row "Type" is = F , the second one when the row "Type" is = T.
The problem that I am having with this code is that it runs the functions ONLY for the first mySQL result.
But I have more results in the same time, and the functions should run for EACH mySQL result and not only for the first one.
I do not know if I need a foreach or whatever. I do not know anything about arrays and php loops.
Thank you.
include_once("../dbconnection.php");
date_default_timezone_set('UTC');
$TimeZone ="UTC";
$todaydate = date('Y-m-d') ."\n";
$time_utc=mktime(date('G'),date('i'),date('s'));
$NowisTime=date('G:i:s',$time_utc);
$MembID =(int)$_COOKIE['Loggedin'];
$DB = new DBConfig();
$DB -> config();
$DB -> conn();
$queryMAIN="SELECT * FROM TableTuit WHERE TimeZone ='".$TimeZone."' AND Date ='".$todaydate."' ORDER BY ID ASC";
$result=mysql_query($queryMAIN) or die("Errore select TableT: ".mysql_error());
$tot=mysql_num_rows($result);
while($ris=mysql_fetch_array($result)){
$text=$ris['Tuitting'];
$account=$ris['IDAccount'];
$memberID=$ris['memberID'];
$type=$ris['Type'];
$id=$ris['ID'];
$time=$ris['Time'];
if($time <= $NowisTime){
if($type=="F") //if the row type is = F, then do the things below
{
$queryF ="SELECT * FROM `TableF` WHERE `memberID`='$MembID' AND `ID`='$account'";
$result=mysql_query($queryF) or die("Errore select f: ".mysql_error());
$count = mysql_num_rows($result);
if ($count > 0) {
$row = mysql_fetch_assoc($result);
DO FUNCTION // Should call the function that requires the above selected values from $queryF. Should Run this function for every mysql result given by $queryMAIN where row "type" is = F
}
}
}
if($type=="T") //if the row type is = T, then do the things below
{
$queryT = $queryF ="SELECT * FROM `TableT` WHERE `memberID`='$MembID' AND `ID`='$account'";
$result=mysql_query($queryT) or die("Errore select $queryT: ".mysql_error());
$count = mysql_num_rows($result);
if ($count == 0)
$Isvalid = false;
else
{
$Isvalid = true;
$row = mysql_fetch_assoc($result);
}
if($Isvalid){
DO THIS FUNCTION // Should call the function that requires the above selected values from $queryT. Should Run this function for every mysql result given by $queryMAIN where row "type" is = T
}
}
}
}//END OF MYSQL WHILE OF $queryMAIN
You are using $result for the outer Query ($result=mysql_query($queryMAIN); and the Query inside the while loop $result=mysql_query($queryF); - I believe you do not want to mix these?
Right now you process the first row from TableTuit, then overwrite the $result with a row from TableF or TableT. In the next loop, the following columns will not be found in the array (unless they are also in these two tables, of course):
$text=$ris['Tuitting'];
$account=$ris['IDAccount'];
$memberID=$ris['memberID'];
$type=$ris['Type'];
$id=$ris['ID'];
$time=$ris['Time'];
You are loading the results into an array, try using this in your while loop instead:
while($ris=mysql_fetch_assoc($result)){
More problems with dates.
Basically I'm trying to populate a table with some datetime values from Zend. The datatype of the column that I'm trying to populate is 'datetime'. However, no matter which constant I try the column is always populated with zeroes. I've tried Zend_Date::ISO_8601, Zend_Date::DATETIME, Zend_Date::now() to no avail. Pleas help.
Here's the code:
if(!$exists){
$date_time = Zend_Date::DATETIME;
/*
* Create the new site record
*/
$site_row = $site_table->createRow();
//if(isset($n_r['id'])) $row->id = $n_r['id'];
$site_row->name = $n_r['name'];
$site_row->active = 1;
$site_id = $site_table->total() + 1;
$address_id = $address_table->total() + 1;
$site_row->id = $site_id;
$site_row->address_id = $address_id;
/*
* Create the address record to go with it
*/
$address_row = $address_table->createRow();
$address_row->postcode = $n_r['postcode'];
$address_row->address_line1 = $n_r['name'];
$address_row->start_date = $date_time;
$address_row->id = $address_id;
$address_row->save();
$array[] = $site_row->toArray();
$site_row->save();
/*
* Create the new site2address record to go with it
*/
$site2address_row = $site2address_table->createRow();
$site2address_row->site_id = $site_id;
$site2address_row->address_id = $address_id;
$site2address_row->start_date = $date_time;
}else{
$array[] = $exists;
}
mySQL expects input for DATETIME columns to be
YYYY-MM-DD HH:MM:SS
independent from the locale you are using. I can't see a Zend constant for that, you may need to format it yourself.
you can use mysql function like NOW() for more convenience way. if you are at mysql code bellow may work for you.
$address_row->start_date = new Zend_Db_Expr('NOW()');
I'm comparing date specified in PHP with dates in MySQL table and then echoing all rows with dates after the date in PHP. It works OK when I specify the date in the SELECT command, but when I make it a variable it doesn't work.
My PHP is:
$sql = "SELECT event FROM LifeEvents WHERE event_date > '1995-02-27'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["event"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
This works ok. But when I replace the SELECT with:
SELECT event FROM LifeEvents WHERE event_date > $date
It no longer works.
For the variable I've tried working with both:
$date = new DateTime('1995-02-27')
and
$date = '1995-02-27'
Neither of them works. The data type in MySQL is DATE.
For the string variable
$date = '1995-02-27'
$sql = "SELECT event FROM LifeEvents WHERE event_date > '$date'";
// this should work exactly as
$sql = "SELECT event FROM LifeEvents WHERE event_date > '1995-02-27'";
For the DateTime object, this should work
$date = new DateTime('1995-02-27')
$sql = "SELECT event FROM LifeEvents WHERE event_date > '" . $date->format(Y-m-d). "'";
I suggest you always set the timezone when you are dealing with dates and times because underestimate timezones can result in really bad bugs specially if your applications is dealing with many timezones and you have timestamp data type in your database.
make it a habit to do this
define('DEFAULT_TIMEZONE','UTC');//set this in your global config.php file
$date = new DateTime('2000-01-01', new DateTimeZone(DEFAULT_TIMEZONE));
Lets create a variable that holds a date and then convert it to date format that MySQL can understand.
$dt = date('Y-m-d', strtotime('1995-02-27')); // maybe filled dynamically
$sql = "SELECT event FROM LifeEvents WHERE event_date > '$dt'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["event"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
Then change what you want in order to serve your needs.
Hope I pushed you further.
That's because '1995-02-27' and DateTime('1995-02-27') are both not valid in that case :
'1995-02-27' would work if you'd have put extra quotes around $date in your SQL query : "SELECT event FROM LifeEvents WHERE event_date > '$date'"
DateTime('1995-02-27') doesn't have a __toString() magic method so PHP is unable to represent it as a string. You have to use the format method : $date = $date->format('Y-m-d') (and it will still miss the quotes)
One or another solution, you need to protect yourself against SQL injections using prepared statements! And you will actually no longer need any quote.
Try using the Carbon library for PHP.
Store a date with PHP:
$current_time = Carbon::now()->toDateTimeString();
Then just compare it the same way.