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!
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'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
I have some data in my table which are [name][address][phone_number] and the date in this format 2015-10-14 14:37:38. I am using php PDO. How can I query out just today date from the table?
The following code is my code to query out result for the past 7 days which worked perfectly. However, whenever I replace it with 1 it doesn't work:
$query = $digital->query('SELECT * FROM sales WHERE `datetime` BETWEEN DATE_SUB(NOW(), INTERVAL 7 DAY) AND NOW() ORDER BY sale_id DESC');
What I want is to be able to query out all today data inserted into database.
You can use this, haven't tested.
<?php
$todaysDate = date('Y-m-d'); //if your date is stored in y-m-d format
try
{
$s = $conn->query("SELECT * from sales where datetime LIKE '%$todaysDate%'");
}
catch(PDOException $e)
{
echo $e->getMessage();
}
$results = $s->fetch(PDO::FETCH_OBJ);
?>
Your query results is now in $results variable.
Extended version
<?php
try
{
$s = $conn->query("SELECT * from sales");
}
catch(PDOException $e)
{
echo $e->getMessage();
}
while($results = $s->fetch(PDO::FETCH_OBJ))
{
$date = explode(" ", $results->datetime);
if($date[0] == date('Y-m-d'))
{
//write code here to display data
}
}
?>
Make sure you replace all the columnNames and tablename.
Edit :-
Here's a sqlfiddle pertaining to my first solution.
http://sqlfiddle.com/#!9/7c2f1/3
I dont know whether it applies to PDO, as I'm not very acquainted to it, but I use to pass the date in a var, then ask for a match in my sql statement
// choose your own timezone here
date_default_timezone_set('America/Sao_Paulo');
// then define your variable as the current time:
$date = date("Y-m-d H:i:s");
then, i'd use the correct PDO syntax to compare the column with the var (a simple "where" statement should do it).
(using codeigniter syntax)
$this->db->where('date', $date);
I have a query like this
select fname,joined_date from employees where id=1
currently the date format I'm using to display this returned employee details is Y-m-d.
But now I need to convert the default mysql format Y-m-d to d/m/Y(in all date information display fields).
For me it's very very difficult to go through all the files to do the date format conversion.
So I thought of doing some thing like this in my database class.I have a function like this in my database class
function fetch($res){
$row = mysql_fetch_assoc($res);
foreach($row as $key=>$value){
if(preg_match('/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/',$value))
$row[$key] = date('d/m/Y',strtotime($value));
}
return $row;
}//end function
and i'm using this function like this
$row = $db->fetch($res);
or
while($row = $db->fetch($res)){...}
I'm getting the expected output,but with an error message
invalid argument for foreach
it looks like the fetch function code executed (total_num_rows + 1) times
If I use for loop instead of foreach, getting undefined offset error
currently I'm using some thing like this to escape
if(is_array($row)){...}
when i look for the type $res,
it showed
resource(1st iteration),resource(2nd)
for $row array
array(1st iteration),boolean(2nd)
Can anybody tell me why it's happening?
Or is there a better way to do this?
Thanks in advance.
When you reach the end of the results, mysql_fetch_assoc() returns false. You need to check for that case:
function fetch($res){
$row = mysql_fetch_assoc($res);
if ($row) {
foreach($row as $key=>$value){
if(preg_match('/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/',$value)){
$row[$key] = date('d/m/Y',strtotime($value));
}
}
}
return $row;
}
if you want this format for ex: June 19, 2015
use this:
date("F d, Y",strtotime($myrow['date']));
where $myrow['date'] is what you are fetching from mysql row wise
check this link for further assistance: http://erikastokes.com/mysql-help/display-mysql-dates-in-other-formats.php
It is easier to have you convert the date to the desired format already in the MySQL command.
example:
SELECT *, DATE_FORMAT(date, "%m-%d-%y") AS date FROM my_table;