I am new to php as well as SQL Server, so if my question is too trivial please bear with me. Our company just migrated database from MySQL to SQL Server 2008. I am having problem retrieving datetime properly from the database. The field in question is of datetime type. The code i use is -
$query = "select name,rdatetime from names order by name";
$result = mssql_query($query);
while($row=mssql_fetch_array($result))
{
$name = $row["name"];
$rdatetime = date('Y-m-d H:i:s',strtotime($row["rdatetime"]));
}
When I print this $rdatetime it shows as 2014-03-07 16:17:00. The ss part is always 00, even when there are other values in the database. I even tried the DateTime object
$rdatetime = new DateTime($row["rdatetime"]);
echo $rdatetime->format("Y-m-d H:i:s");
But the results are same. Can anyone tell me what can be the problem ?
Related
I have a crazy phenomenon in my php script. I have defined a column as a timestamp in a mysql table. I fill it with the function:
date("Y-m-d H:i:s");
The data in the table then look like this: 2017-04-19 17:08:45
When I query this column with mysqli as a unix timestamp again:
SELECT UNIX_TIMESTAMP (timestamp) as timestampUnix FROM posts
Then binding the result using bind_result to the variable $timestampUnix.
I can echo the variable with
echo $timestampUnix;
and it outputs a correct timestamp like this: 1492614559
however if i do the following:
$timestampUnix2 = $timestampUnix;
echo $timestampUnix2;
there is simply no echo output... What is the reason?
I tried this because I actually want echo only the date in an other format with:
date('d.m.Y', $timestampUnix)
and it gave me 01.01.1970 and i wondered why the timestamp must be 0 but it isnt since when i directly echo it it gives me a correct one.
however when i do
Date('d.m.Y', 1492614559)
it gives me the correct date.. no clue what is going on there!
i know there are many other questions about mysql php Date output, but no one have this issue as i think i cannot do something with the variable i got from the query.
thanks in advance!
edit: i attach the complete code in question:
---the query that inputs the data in the db----
$timestamp = date("Y-m-d H:i:s");
mysqli_query($mysqli,"INSERT INTO posts (timestamp)
VALUES ('$timestamp')");
---the query that fetches the data----
$results = $mysqli->prepare("SELECT UNIX_TIMESTAMP(timestamp) as timestampUnix FROM posts");
$results->execute(); //Execute prepared Query
$results->bind_result($timestampUnix); //bind variables to prepared statement
$postdate = date('d.m.Y',$timestampUnix)
echo $postdate;
Hey guys it may have been asked before but I am still stuck with a peculiar issue.
I am trying to Pass a dateTime object to my mysql insert statement but it always tells me there is an error namely:
Object of class DateTime could not be converted to string
$dateToPass = new DateTime('now');
//$dateToPass = $dateToPass->format('d/m/Y H:i:s');
//inserting values
$SQLstring="Insert into Request(cust_num,request_date,item_description,item_weight,pickup_address,pickup_suburb,
pickup_date,pickup_time,receiver_name,delivery_address,delivery_suburb,delivery_state)
values(27,$dateToPass,'$desc',$weight,'$address','$suburb','$date', '$time','$rname','$raddress','$rsuburb','$rstate');";
$queryResult = #mysqli_query($DBConnect, $SQLstring)
Or die ("<p>Unable to query the Customer table.</p>"."<p>Error code ". mysqli_errno($DBConnect). ": ".mysqli_error($DBConnect)). "</p>";
Where $dateToPass is a datetime field in my database.
Hope you guys can help.
you cannot send DateTime object as string. Try converting it to string as MySQL expects.
$dateToPass = new DateTime('now');
$dateToPass = $dateToPass->format('Y-m-d H:i:s');
Alternatively if you are always going to store current datetime you can use the MySQL NOW() like
$SQLstring="Insert into Request(cust_num,request_date,item_description,item_weight,pickup_address,pickup_suburb,
pickup_date,pickup_time, receiver_name,delivery_address,
delivery_suburb,delivery_state)
values(27,NOW(),'$desc',$weight,'$address','$suburb','$date', '$time','$rname','$raddress','$rsuburb','$rstate');";
I am trying to search record in mysql based on date which is submitted hidden field in a form, but I haven't got any results from DB with given date, I know there is a record with the same date.
I have a following code:
$id = $_POST['pid']; //hidden field in form with sample value 1
$d = $_POST['d']; // hidden field in form with sample value 2014-12-17 18:25:58
$ch = $con->query('SELECT * FROM '.PATDMBILL.' WHERE pid='.$id.' AND pfid=0 AND date="'.$d.'"');
In DB date column is current time-stamp.
When I assign $d to this value '2014-12-17 18:25:58' it works but from submitting form it will not work.
So Where I am making a mistake ?
I hope I have cleared my situation properly.
Rewrite the code:
$id = $_POST['pid'];
$d = $_POST['d'];
$query = 'SELECT * FROM '.PATDMBILL.' WHERE pid='.$id.' AND pfid=0 AND date="'.$d.'"';
echo $query;
$ch = $con->query($query);
You will then be able to see if the query is actually formatted properly and fix any obvious issues. Unfortunately there isn't enough information to say what the solution is, but you should be able to copy and paste the echoed 'query' and paste it into the tool you use to build queries (eg phpmyadmin or sequel pro)
The problem may be occurring because of the time 18:25:58 . You can change the database field from timestamp to date and pass only date from $d using strtotime(date("Y-m-d", $d));
I am trying to compare a stored date to the current date, and send back data accordingly. I'm not fluent in PHP so this is what I have so far
while ($row = mysql_fetch_array($result)) {
// temp user array
$event_date_str = $row["date"];
$todays_date_str = date("m-j-Y");
$today = strtotime($todays_date_str);
$event_date = strtotime($event_date_str);
if($event_date > $today){
$event = array();
$event["pid"] = $row["pid"];
$event["name"] = $row["name"];
$event["longitude"] = $row["longitude"];
$event["latitude"] = $row["latitude"];
$event["pavement"] = $row["pavement"];
$event["traffic"] = $row["traffic"];
$event["environment"] = $row["environment"];
$event["image_b64"] = $row["image_b64"];
$event["created_at"] = $row["created_at"];
$event["date"] = $row["date"];
$event["time"] = $row["time"];
$event["type"] = $row["type"];
// push single product into final response array
array_push($response["events"], $event);
}else{
//delete it here
}
With that code right there I am getting nothing back. I have 2 items stored in the database, One with the date "2-28-2014" and another with "2-14-2014", so I should be getting one back and not the other but I am getting neither back. I know that there are no leading zeros with the dates saved so I should use j right? Could someone help me figure out why this is not working, sorry if it seems like a simple question.
Thank you in advance,
Tyler
This is not an efficient way to do things. If you need to pick items based on date, do it in the MySQL query directly. PHP filtering will always be slower than MySQL. Especially since you have to deliver extra data over network when filtering at PHP level.
So do it like this:
SELECT * FROM `table` WHERE `record_expires_datetime_gmt` > UTC_TIMESTAMP();
SELECT * FROM `table` WHERE `record_expires_date_gmt` > DATE(UTC_TIMESTAMP());
// use NOW() for local time, UTC_TIMESTAMP() is GMT/UTC
Then do what you need to do with the records. Never SELECT * and then filter records in PHP.
There's a whole set of DATETIME functions in MySQL to allow you MySQL server side filtering of data.
PS: Obviously, for this method to work, your MySQL table has to be properly designed. Date (date and time) fields need to be of type DATE or DATETIME not surrogate strings that are meaningful only within your project.
I have a database which id,title,subject and datetime and I'm calling a php page that takes in a request from clients to show the latest entry in the db from the difference of time from the client and checks with the last entry's datetime. PHP code as follows
$date = "2012-10-06 18:13:52";
//Establish a connection
$conn = mysql_connect('localhost','regadmin','regadmin');
//Select the mySQL db
$db = mysql_select_db('easy_comm', $conn);
$sql = mysql_query("SELECT `title`, `subject`,`date_sent` FROM `books` WHERE `date_sent` > '$date'", $conn);
$count=mysql_num_rows($sql);
if($count != 0){
$json = array('boolean' => true);
}
else{
$json = array('boolean' => false);
//echo "No record";
}
From the above code and the provided $date variable, it will always return true and the last entry is
2012-10-06 18:10:52
I have tried converting to UNIXTIMESTAMP but same problem
Well this works good enough for me.Please make sure the column against which you are comparing the date surely happens to be DATETIME column not a VARCHAR or something else.
Please post us database structure to see the collation as well and also try printing the query on the fly and then execute in your console.