DateTime being passed to insert query in PHP not working - php

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');";

Related

mysql timestamp output as formatted Date not working

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;

Trying to make a stored Datetime value shorter with SQL Convert function

I'm new to using the convert function. I'm trying to make a datetime value from my table shorter. Currently my datetime values look something like this, 2016-10-14 16:51:41, but I'd like to make it look something like mm/dd/yy.
I don't know if this is the right approach (must not be since it doesn't work), but I've generated a query using the convert function and then fetching the data with a mysqli_fetch_array.
Here's the code I'm using:
$sql = "SELECT id, time, CONVERT(VARCHAR(11), time) as something FROM tableName";
$query = mysqli_query($db, $sql);
$statusnumrows = mysqli_num_rows($query);
// Gather data about parent pm's
if($statusnumrows > 0){
while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
$time= $row["time"];
}
}
Time is the name of the column which has the datetime type.
Thanks in advance, for suggestions/advice.
You should store datetime in your DB in proper data types like datetime etc.
As I can see you are using PHP, if you need to OUTPUT this datetime in some interface (f.e. HTML page), you should use PHP functions to convert date in format you need. That is the good practice
DB should STORE the data but formatting is front-end problem.
Simple example of strtotime() and date():
$Date = "2016-10-15";
$newDate = date("m/d/Y", strtotime($Date));
You can read docs on the PHP site: strtotime and date
If 2012+ you could use format (not very efficient but does offer some other possibilities)
Declare #Date DateTime = GetDate()
Select UsingFormat = Format(#Date,'MM/dd/yy')
,UsingConvert1 = convert(varchar(10),#Date,1)
,UsingConvert101 = convert(varchar(10),#Date,101)
Returns
UsingFormat UsingConvert1 UsingConvert101
10/15/16 10/15/16 10/15/2016
Use style 1 in Convert function for mm/dd/yy format
select CONVERT(VARCHAR(20), [time],1)
From yourtable
If you want mm/dd/yyyy format then use 101 style
select CONVERT(VARCHAR(20), [time],101)
From yourtable
MSDN link for Convert function with various style : CONVERT

Not able to retrieve seconds from SQL server using PHP

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 ?

Insert DATE as DATE->Format() in Mysql

I' trying to insert a DATE into MySQL database. Date has been set as new DateTime() and formatted to "Y:m:d". A variable carries the new DateTime but when inserting it to a DATE field in MYSQL only ceros are inserted. The DATE field is not getting NULL results but just CEROS 000-00-00.
This is my code.
$bigin=date("Y-m-d");
$datetime_bigining = new DateTime($bigin);
$datetime_bigining->modify('-60 day');
$datetime_bigining->format('Y:m:d');
$insert_days= mysql_query("INSERT INTO $tocreate (date_full) VALUES".$datetime_bigining->format('Y-m-d').");") or die(mysql_error());
Your code can be simplified tremendously (and fixed):
$datetime_beginning = new DateTime('60 days ago');
$insert_days= mysql_query("INSERT INTO $tocreate (date_full)
VALUES ('".$datetime_beginning->format('Y-m-d')."');") or die(mysql_error());
You can combine your first three lines of code
Your fourth line is unnecessary and useless
You have a couple of SQL syntax errors (missing parenthesis, missing quotes)
Try $datetime_bigining->format('Y-m-d'); This is the format that MySQL expects.

how to retrieve a sql datetime object with a php $row?

For instance:
$sql = "SELECT * FROM db";
$query = sqlsrv_query($conn, $sql);
while($row = sqlsrv_fetch_array($query)){
echo "$row[date_column]";
}
will crash
Most of the answers I've found are assuming you want to order your query by a datetime, but I just want to turn the datetime object into a string after I have all the rows.
I don't really understand how to use the php date() function,
I've tried:
echo date("m/d/Y",$row[date_column]); //prints nothing
$string=$row["date_column"]->format('Y-m-d H:i:s')
while($row=sqlsrv_fetch_array($rs,SQLSRV_FETCH_NUMERIC))
{
$logdate=date_format($row[4],"Y-m-d H:i:s");
}
here, $row[4] contains the date object. This would surely help.
First of all, if "date_column" is the column name, it should be in quotes, like this:
echo $row["date_column"];
Secondly, PHP has a built-in function to turn MYSQL datetime into a unix timestamp, which PHP date() can use. Try this:
echo date("m/d/Y", strtotime($row["date_column"]));
Cheers!

Categories