Format Date field type - php

i have a csv file that i'm interest and the date format is 20-Nov-2010 how do I format it for insertion into mysql accepted format for a field with Date as its type?

date("Y-m-d", strtotime("20-Nov-2010"));

Andreas' answer is a bit terse - in PHP this will return a string which you can splice
into your query:
$d=date("Y-m-d", strtotime("20-Nov-2010"));
$qry="INSERT INTO sometable (adate) VALUES('$d')";
But if you omit the punctuation, you can ad it without the quotes:
$d=date("Ymd", strtotime("20-Nov-2010"));
$qry="INSERT INTO sometable (adate) VALUES($d)";
A drawback of this approach is that strtotime() tends to always return some sort of date value - and sometimes not what you expect.
However you could do the parsing in MySQL, which is a lot more strict:
$d='20-Nov-2010';
$qry="INSERT INTO sometable (adate) VALUES(STR_TO_DATE($d, '%d-%b-%Y'))";
But remember to check for errors when mysql tries to parse the date.

Related

oci_execute(): ORA-01840: input value not long enough for date format

I am currently receiving the following error message from oci in php (I've been on it for a few hours).
oci_execute(): ORA-01840: input value not long enough for date format
It strange, because when I run the query within SQL Developer it seems to work fine.
This makes me think that when I bind the parameter it is turning the dates into a type that is not able to calculate using conventional operators in oracle.
$startDateTime = '2015-03-06 00:00:00';
$endDateTime = '2015-04-06 00:00:00';
$value = '20';
$type = '$';
$SQL = "SELECT count(*) AS \"COUNT\"
FROM bonus where value = :d_value
AND TYPE = :d_type
AND ((:d_valid_from between valid_from AND valid_till) OR (:d_value_till between valid_from AND valid_till) OR (:d_valid_from < valid_from AND valid_till < :d_valid_till))";
$this->stmnt = $this->conn->prepare($SQL);
$this->stmnt->bindParam('d_valid_from', $startDateTime);
$this->stmnt->bindParam('d_valid_till', $endDateTime);
$this->stmnt->bindParam('d_value', $value);
$this->stmnt->bindParam('d_type', $type);
$this->stmnt->execute();
I am unable to find many resources that deal with php directly with this problem in hand. Does anybody have any experience with it?
I think that your dates are being bound as strings in the query. Assuming that the columns you are comparing it to (e.g. valid_from) are dates, then the string value is being converted to a date using the default date format for the sessions. The difference in behavior in SQL Developer is probably because the default format is different.
Anyway, the solution is to follow a very simple and important rule, which is not to rely on default type conversion. Explicitly convert the string to a date in your query, specifying the appropriate format:
TO_DATE( :d_valid_from, 'YYYY-MM-DD HH24:MI:SS' )

Zend 1.12: How to Format Date upon SQL Select

This question may be in part a duplicate of How to convert the system date format to dd/mm/yy in SQL Server 2008 R2?, but I could not get any of the answers there working in my code. We're using MySQL 5.0.95, I don't know if that makes a difference, but I couldn't find a definitive answer that solved my problem.
Here's my code:
public function getZipCodes() {
// get records
$select = new Zend_Db_Select($this->db);
$select->from('postal_codes AS p', array(
'p.postal_code',
'p.city',
'p.county',
'p.area_codes',
's.rate',
// convert from datetime to mm/dd/yyyy format <== problem here
'CONVERT(varchar(11), s.date, 101)'))
->joinInner('sales_surtax_rates AS s', 'p.county = s.county', array())
->where('p.state = "FL"')
->order('p.postal_code');
$zip_codes = $this->db->fetchAll($select);
Zend_Debug::dump($zip_codes);
die();
}
I get a syntax error when trying to convert the datetime to a formatted string. I'm just not seeing what I'm missing, and other methods like FORMAT and cast didn't work for me either.
I'm well aware I can just loop through and reformat the datetime via PHP for each array item after pulling the records from the database, but I'm just trying to avoid the extra step(s) if I can and learn something new in the process.
You're using MSSQL syntax, it would appear, NOT MySQL's.
Try
DATE_FORMAT(s.date, '%m/%d/%Y')
instead.
Relevant docs: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format

Filtering by date range in SQL query

I am unable to get the following code to work:
// dd/mm/yyyy for dates in SQL queries
$todayforw = date('d/m/Y');
$aweekago = date('d/m/Y', time() - 604800);
$week_e_check = mysql_query("SELECT * FROM earningslog WHERE user_id = '".$info['id']."' WHERE day >='".$aweekago."' AND day <'".$todayforw."'");
while ($week_e_info = mysql_fetch_array($week_e_check)) {
$week_e = $week_e + $week_e_info['user_earnings_amnt'];
}
The query returns zero rows, however, it should be returning data that matches the criteria.
Check your date format:
Should be:
YYYY-mm-dd HH:mm:ss
E.G.
2012-01-01 00:00:00 (January 1, 2012 at midnight local time)
Other date formats MAY work, but the best way to go about it is to use the same format that MySQL uses when they display the date, that's the only way I know that works every time.
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html
Also your syntax is incorrect, you have two wheres, you should use AND.
Take a closer look at your query:
SELECT * FROM earningslog WHERE user_id = '".$info['id']."' WHERE day >='".$aweekago."' AND day <'".$todayforw."'"
Your Where clause appears twice.
Two things to think about - when you are selecting data, try and stay away from select * - you may get unexpected results of the table is ever modified.
Second, try and create the query as a parameterized query, instead of injecting the parameters directly into the where clause. By directly injecting your criteria the way you have, you are opening yourself up to a SQL injection attack.
By turning it into a parameterized query, you get the side benefit of being able to debug the queries directly against the database, reducing the amount of effort needed to copy it from a query tool into your code.
Your issue appears to be with your query syntax. You are stating WHERE twice, whereas you should only state it once and then use the AND or OR operators for further criteria. I would also suggest that you either move your statement into a variable or use die() to assist with debugging.
$week_e_check = mysql_query("SELECT * FROM earningslog WHERE user_id = '".$info['id']."' AND day >='".$aweekago."' AND day <'".$todayforw."'") or die(mysql_error());
In addition, you should not be using the mysql extension as use of this extension is discouraged. Instead, use the MySQLi or PDO_MySQL extension. Using one of these alternative extensions will help serve as the first step in preventing SQL injection. I would also suggest that you avoid using * and specify the column names to be returned instead.
Using PDO:
<?php
/* Execute a prepared statement by passing an array of values */
$sth = $dbh->prepare('SELECT * FROM earningslog WHERE user_id = ? AND day >= ? AND day < ?');
$sth->execute(array($info['id'], $aweekago, $todayforw));
$results = $sth->fetchAll();
?>
Try change the format of your strings from from d/m/Y to Y-m-d.
MySQL might be expecting it year first. In which case it could be doing the wrong thing with d/m/Y.
Also don't use the WHERE clause twice. Instead, combine conditions using AND, eg:
WHERE user_id = '".$info['id']."'
AND day >='".$aweekago."'
AND day <'".$todayforw."'
By the way, you can also try saying WHERE day BETWEEN ".$aweekago." AND ".$todayforw.", which might be easier syntax to read (as long as you change $todayforw to be the day before).

Compare string datatype to a date datatype PHP MYSQL

In my MySQL database, I have this Time data type as one of my values: 06:00:00. I have the following query that checks the time as one of the conditions that has to be satisfied
$time = "06:00:00";
$getdetails=SELECT First_Name, Last_Name, EMAIL
FROM parents
WHERE Email_Receive_Time = $time;
$results=mysql_query($getdetails);
However I do not get any results. On further research I have seen that it is because I am comparing a STRING type value ($time) to a TIME type value (value in my database). Is there a way i can compare the two without changing my database structure to a varchar? All help will be appreciated.
MySQL is perfectly capable of comparing a string to a TIME value. You just need to have the proper query syntax. In your case, you need to quote the comparison value:
$time = "06:00:00";
$getdetails = "SELECT First_Name, Last_Name, EMAIL
FROM parents
WHERE Email_Receive_Time = '$time'";
$results=mysql_query($getdetails);
And if it is user-supplied, well you should escape it.
You are wrong.
Your mistake is much simpler, it has nothing to do with data formats, but with query format.
Ask yourself what does mean 06:00:00 in terms of SQL syntax.
Btw, running query this way will help you A LOT:
$results=mysql_query($getdetails) or trigger_error(mysql_error()." in ".$getdetails);
always run all your queries this way and get in touch with every error occurred
This will work when comparing against TIME type of field:
To compare against DATETIME or TIMESTAMP, I'd suggest running the $time variable through strotime() first.
$time = "06:00:00";
$getdetails = "SELECT First_Name,
Last_Name,
EMAIL
FROM parents
WHERE Email_Receive_Time = '$time'";
$results = mysql_query($getdetails);
Try using STR_TO_DATE function, it should work for you.
Thanks
Ravi Mudaliar

Formating multiple mySQL date fields at the same time

I have a table with 12 timestamp columns and 3 other fields.
I can't change the field type on the timestamp columns.
I need to display all 15 fields to the user as m/d/y. Is there a way to format them all at the same time without having to apply DATE_FORMAT to each one?
I'd rather not have to do
SELECT DATE_FORMAT(field, '%c/%e/%y') AS field
for each one if possible.
I'm using mySQL & PHP and I don't care where the conversion happens.
You can write a simple date conversion routine in php such as this:
function mysql2table($date) {
$new = explode("-",$date);
$a=array ($new[2], $new[1], $new[0]);
return $n_date=implode("-", $a);
}
Which I stole from here: http://www.daniweb.com/code/snippet736.html#
Then simply loop through your SQL column results checking if the value is a date and converting it.
Have you considered using a database layer like MDB2 or PDO, which can convert the types for you? MDB2 has a date type, that displays YYYY-MM-DD format but could easily be turned into m/d/y with strftime and strtotime.
An example of using MDB2:
$dsn = "mysql://user#pass/db"; (not sure about DSN format, you might have to poke the MDB2 documentation)
$connection = MDB2::connect ($dsn);
$connection->loadModule ("Extended");
$rows = $connection->getAll ("your query", array ('date', ...), $parameters, array (paramater-types), MDB2_FETCHMODE_OBJECT);
if (MDB2_Driver_Common::isError ($rows)) throw new Exception ("Error!");
else { foreach ($rows as $row) { ...Do something... } }
You can find more documentation about using MDB in this way at MDB2 on InstallationWiki. Also there you'll find a list of MDB2 datatypes and what they are mapped to for display values. Also, Docs for MDB2_Extended will be a good source of info.
Edit: Obviously you'll have to use strftime and strtotime on each row separately. If you switch MDB2_FETCHMODE_OBJECT to MDB2_FETCHMODE_ORDERED or MDB2_FETCHMODE_ASSOC above, you can probably use a foreach loop to run strftime and strtotime on all of the rows that need to be reformatted.
I dont think it is possible, the query doesnt know what columns are until it returns the results, you have to tell it to change the formatting for each datetime.
Matt

Categories