PHP strtotime returns empty value - php

Well i built my website to write dates to database column in the following format:
2014/04/01
Now i've come to realize this is not helpful when i want to sort by date or manipulate date so i decided to change all date to to timestamps.
i applied the following fix :
$sql = mysql_query("SELECT * FROM TABLE")or(die(mysql_Error()));
while($info = mysql_fetch_array($sql)){
$newdate = strtotime($info['date']);
mysql_query("UPDATE TABLE SET date = '$newdate' WHERE id = $info[id]")or(die(mysql_error()));
}
the problem is all the date columns are empty now, What am i doing wrong ?

There's what looks like a syntax error on this line:
mysql_query("UPDATE TABLE SET date = '$newdate' WHERE id = $info[id]")
or(die(mysql_error()));
Try changing it to:
mysql_query("UPDATE TABLE SET date = '$newdate' WHERE id = {$info['id']}")
or (die(mysql_error()));
The reason is that when interpolating array indices into a string, you must surround them with {} or PHP will just try to convert $info to a string and insert [id] after it, which I'm guessing you didn't intend.
I would also suggest checking the return value for strtotime. If it can't parse a date it returns false which I'm guessing you don't want inserted back into your database.

Related

how to get one record from a mysql database with php

i'am trying to get one cell from my mysql database.
this cell is unique because of the date and hour.
so if date and time is selected with a WHERE it should come back with one number.
I checked everything but it still doesnt work. i get zero returns.
does anyone see something wrong with my code?
$result2 = mysql_query("SELECT * FROM `chairs` WHERE `date` = '$date' AND `hour` = '$hour' ");
$row = mysql_fetch_array($result2);
$dbchairs = $row[$chairs];
echo $dbchairs;
You have undefined variable chairs in
$dbchairs = $row[$chairs];
If in DB is column called chairs, use:
$dbchairs = $row['chairs']; // key of $row array is column name
change this
$dbchairs = $row[$chairs];
to
$dbchairs = $row['chairs'];
You are using undefined variable $chairs as your index in $row array.
syntax: $row['name_of_the_column_in_database']

Mysql Get table result between two dates

I know my question is similar to other question already answered but my issue is different because I need some alternative or advice no how to go the other way around.
My issue is: I want to get values between either two dates or one according to what user wants..
When User request data of one day.. php query data successful.. but problem is when data requested is between two dates..
$query = $this->db->query("SELECT * FROM `meta_receipt_data`
WHERE `meta_transaction_date` >= '$first_date' AND
`meta_transaction_date` <= '$second_date' ");
return $query->result();
I get an empty set...
So I thought may be the values are not submitted correct.. so I echoed the values to see if they are correct or not. I find they are correct...
$first_date = 09/13/2014;
$second_date = 09/19/2014;
But if I try to put the value like
$query = $this->db->query("SELECT * FROM `meta_receipt_data`
WHERE `meta_transaction_date` >= '09/13/2014' AND
`meta_transaction_date` <= '09/19/2014' ");
return $query->result();
I get my result back correct.. so is there anything am doing it wrong??
Change the type of meta_transaction_date to DATE as that is what it is! Also use the standard 'yyyy-mm-dd' when passing in DATEs.
Your problem probably stems from string ordering of the 'mm/dd/yyyy' US date format which is horrible for coding. If you wish to display the DATE in this format, convert it when SELECTing the final output.
MySQL has a built in function called Between that you can use like this:
SELECT * FROM table_name WHERE date_column BETWEEN 'start_date_parameter' AND 'end_time_parameter'
Try to cast the date first , and then with between statement:
$query = $this->db->query("SELECT * FROM `meta_receipt_data`
WHERE `meta_transaction_date` BETWEEN
date_format(str_to_date('$first_date', '%d/%m/%Y'), '%Y-%m-%d') AND
date_format(str_to_date('$second_date', '%d/%m/%Y'), '%Y-%m-%d')");
$query = $this->db->query("SELECT * FROM `meta_receipt_data`
WHERE `meta_transaction_date` >= '09/13/2014'
AND `meta_transaction_date` <= '09/19/2014' ");
Since the above seems to be working fine, the problem is in your code.
$query = $this->db->query("SELECT `meta_transaction_date` FROM meta_receipt_data WHERE
meta_transaction_date BETWEEN "
.date( "Y-M-d", ( strtotime($first_date) ) )." AND "
.date( "Y-M-d", ( strtotime($second_date) ) ) );
A word of advice, do not use queries like SELECT * as they will degrade performance of your application. And I just read in your comment to your own question:
I have set the type as Varchar
Do not do that. It is best to use the DATE type to store dates. You can use the query:
ALTER TABLE `meta_receipt_data`
MODIFY `meta_transaction_date` DATE NOT NULL;`
Well, that is assuming you wish to keep the column to not accept null values.
I found that the value had space before and after so I use $first = trim($first_date); and problem solved...

PHP Select Date Column from SQL

I am having some trouble getting a date field out of my SQLServer using PHP and have not been able to Google a solution. I know that it involves the fact that the field is a date data type in my table, but the only results I get is a 500-Internal Server Error.
Here is what I have:
$query = "SELECT EntryDate FROM Table1 WHERE UserID = 1";
$result = sqlsrv_query($link, $query);
while($row = sqlsrv_fetch_array($result))
{
echo $row['EntryDate'];
}
This works with every other column in my table except the date column. Any idea why?
BTW, the date in my table is formatted as yyyy-mm-dd.
$row['entryDate']
seems to be an object of type DateTime which you can't print out directly. Try to convert it into a string in order to echo it.
echo $row['entryDate']->format('Y-m-d H:i:s');
or
echo date_format($row['entryDate'], 'Y-m-d H:i:s');
PHP: DateTime::format

MySQL Query Interpret Date String as Date

I saw a couple of posts on this problem, but I'm not getting it to work correctly. I have a PHP variable that I initially POST as a string. To be able to handle a one week date range, I am converting this using strToTime into datetime format (e.g. July 22, 2013 echos as 1374476400).
My table has its dates stored as text in a Y-m-d format (e.g. July 22, 2013 is stored as 2013-07-22). I need to run a query comparing these two values to find dates that fall within my one week range, so I am trying to convert that text into datetime format for comparison purposes.
Here is the SQL that I am using:
$wk_begin = $_POST['wk_begin'];
$wk_begin = strToTime($wk_begin);
$wk_end = $wk_begin + 8;
$sql = "SELECT * FROM myTable WHERE (DATE(date)>=$wk_begin AND DATE(date)<$wk_end)";
I'm not getting any errors, but my query isn't picking any records up, even though i know that there are 7 matching records in the table. So I have two questions:
1) Is there a better way to go about this?
2) If I am on the right track, how can I get the sql statement to convert the text based dates into a big integer so that I can do the comparison correctly.
Any help is appreciated. Thanks!
EDIT: Thanks for all of the suggestions. I've changed the table so that the dates are stored in 'date' format (no more strings). Here is the updated code. Still not picking up any values:
$wk_begin = $_POST['wk_date'];
$wk_end = $wk_begin + 7;
$sql = "SELECT * FROM Workouts WHERE 'date' BETWEEN '$wk_begin' AND '$wk_end'";
date is a reserved word in mysql, to use it as a field name surround it in backticks.
Also your variable insertions need to be surround in apostrophes
SELECT * FROM myTable WHERE (DATE(`date`)>='$wk_begin' AND DATE(`date`)<'$wk_end'
A better solution (in addition to making the date field a date field) would be to use the db library's escaping and quoting mechanisms when building the sql statement.
Also since you are storing your dates in Y-m-d format the cast to date is unneccessary since string comparison on dates formated this way evaluate the same as the string. So
$sql = "SELECT * from myTable WHERE `date` >= ".$db->quoteAndEscape($wk_begin)." and `date` < ".$db->quoteAndEscape($wk_end);
UPDATE
Based on this date can be used as an unquoted field name.
<?php
$wkbegin = $_POST['wk_begin'];
$wk_begin = strToTime($wkbegin);
$d=date('j', $wk_begin)+8;
$m=date('n', $wk_begin);
$y=date('Y', $wk_begin);
$wk_end = date('Y-m-d', mktime(0,0,0, $m, $d, $y));
$wkbegin = date('Y-m-d', $wk_begin);
$sql = "SELECT * FROM `myTable` WHERE `date`>='".$wkbegin."' AND `date`<'".$wk_end."'";
?>

php mysql datetime

I have two tables in MySQL, and each table has its own datetime field.
I want to copy the datetime of table A to overwrite the datetime of table B.
I use PHP.
$result = mysql_query("select *
from A
where id = $key");
$row = mysql_fetch_array($result);
print $row[2]."\n"; // $row[2] is the datetime field
mysql_query("update B
set date_cal = $row[2]
where id = $key") // try to overwrite datetime in table B
$row[2] has the string representation of datetime field.
But the overwrite operation does not take effect. How to do to overwrite datetime field of table B using php?
If I insist using $row[2] to assign the new datetime field rather running mysql_query again, how to do?
I believe you'll need to wrap the date in quotes in your update query.
mysql_query("update B set date_cal=$row[2] where id=$key")
Should be
mysql_query("update B set date_cal='$row[2]' where id=$key")
On another note, I'd suggest that you don't access your fields by index when you're doing a SELECT * query. If you add another field to your database, $row[2] could end up referring to something else. If you instead call $row = mysql_fetch_assoc($result);, you can refer to it by field name, eg
mysql_query("update B set date_cal='{$row['date_field]}' where id=$key")
If I understand that correctly, you can do the same from within your query:
update B
set date_cal = (select date_cal from A where id = {$key})
where id = $key

Categories