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
Related
Trying to make a little Search feature for a user, so he can type in a date on a webpage made with HTML/PHP, and see which people in the db have registered as member on or after (a date). My user inputs the date in format 2015-10-01. This gets sent to a PHP page with a jqxGrid on it, populated with member details of members conforming to my query on the MySQL database (using PDO).
The query uses the operator >= on a string passed as (for example) "2015-10-01" in the WHERE clause, so I am using STR_TO_DATE to make the comparison work:
WHERE `lastUpdated` >= STR_TO_DATE( ? , '%Y-%m-%d');
With PDO, the ? later gets bound to the date (which was passed in as a string).
The db column for registration date is in DATETIME format, and in the db values look like: "2015-10-12 17:12:52".
My query returns an empty array every time, - and this after many hours of trying every conceivable permutation of date format, both in the MySQL statement and on the page that prepares the data for populating the grid.
Can someone show me what's wrong here?
Thanks!!
SP
Make it
WHERE `lastUpdated` > ?
and check your data and stuff.
Basically, you should never touch PDO until you get raw SQL to work.
okay, so here is the PDO version that works - passing in ? instead of the date:
function getJSONAllMembersByDate($PDOdbObject, $regDate)
{
try
{
$membersByDateSQL = "SELECT `id`, `name_first`, `name_last`, `organization`,`email`, `phone`,`source`,`comments`,`language_id`, `lastUpdated` FROM `member` WHERE lastUpdated>=?";//'$regDate'
$get=$PDOdbObject->prepare($membersByDateSQL);
$get->execute(array($regDate));
$rows = $get->fetchAll(PDO::FETCH_ASSOC);
$json=json_encode($rows);
return $json;
}
The fact that it works proves there were other errors in the file containing the jqxwidget (the version before I posted here). I certainly tried about a million different things to get this working.
I don't know if this counts as an answer, but at least it WORKS! There are so many variables in this problem - json, jqxgrid, pdo ... not forgetting that there are several ways to use PDO. I probably had several errors in different places.
(#apokryfos, the STR_TO_DATE was indeed unnecessary.)
In the end, this is what works:
In the PHP page containing the jqxGrid, the url sent to the server is:
url: 'my-json-responses.php?fct=getJSONAllMembersByDate®Date=<?php echo $fromDate ?>'
This $fromDate comes from the $_POST when the user typed in a date (in the format 2015-10-01) on the input page. When the PHP page containing the jqxGrid loads, it does
$fromDate = $_POST['regDate'];
The url "transits" through the file my-json-reponses.php, which contains many functions. It finds the right one:
if ($_GET['fct'] == 'getJSONAllMembersByDate')
{
$result = getJSONAllMembersByDate($connectionObject, $_GET['regDate']);
echo $result;
}
The $result is called on the file that contains all my PDO database requests, including:
function getJSONAllMembersByDate($PDOdbObject, $regDate) { try
{
$membersByDateSQL = "SELECT `id`, `name_first`, `name_last`, `organization`,`email`, `phone`,`source`,`comments`,`language_id`, `lastUpdated` FROM `member` WHERE lastUpdated>='$regDate'";
$get=$PDOdbObject->query($membersByDateSQL);
$rows = $get->fetchAll(PDO::FETCH_ASSOC);
$json=json_encode($rows);
return $json;
}
catch (PDOException $e)
{
echo "There was a problem getting all members with this search query.";
echo $e->getMessage();
}}
Note that I couldn't make the version using "?" in the query work at all, hence passing in the variable $regDate directly, with single quotes around the variable just to make life interesting.
This returns a nice list of all my users as of 2015-10-01 - but is presumably still open to MySQL injection attacks ...
But after this marathon of debugging I am happy enough for now. (All improvements welcomed, naturally!)
SP
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' )
I am having a bit of trouble writing a mysqli query that queries between dates.
The column in my mysql database is a datetime column.
The query I have written in php looks like this
$sessions = mysqli_query($db,"SELECT s.idSession, s.idUser,
FROM rempad.Session AS s WHERE s.idUser = 12 AND s.start BETWEEN '2013-04-28' AND '2013-05-28'");
I have tried escaping the dates like \'2013-04-28\'
I have also tried casting as datetime like: DATETIME(s.start) BETWEEN DATETIME('2013-04-28') AND ...
But that doesn't work.
I have tested the SQL syntax in Mysql workbench so I know that the query returns values, but I can't seem to get it right in php.
Any ideas? I can't find any examples online.
Thanks in advance
L
I tried it and it worked as:
query($db,"SELECT s.idSession, s.idUser
FROM rempad.Session s WHERE s.idUser = 12 AND s.start BETWEEN '2013-04-28' AND '2013-05-28'");
Removed a comma and 'as' after table name.
I have the same problem but a little different from Neil problems (Error when trying to insert date into datetime column),
Neil want to get now date time so he can use CURRENT_TIMESTAMP or GETDATE().
My question is, how if I have string of date like:
$date = '2011-03-29';
then I want to insert into SQL Server database using a stored procedure with PHP.
insert into tbl(date)
values($date)
Can anybody help? Thanks
Just fyi, I have
SQL Server table:
CREATE TABLE tbl
(
date datetime
)
Stored procedure:
create procedure sp_insertdate
(#date datetime)
as
begin
insert into tbl(date) values(#date)
end
PHP code:
<?php
$date = '2011-03-29';
include("con.php");
$query = mssql_init("sp_insertdate");
mssql_bind($query, "#date", &$date, SQLINT4); //sqlint4 for datetime
mssql_execute($query);
?>
The result is 1900-1-1,
I have tried to send the varchar (in php) first then convert to the datetime (in stored procedure) but there is some error.
Really I'm stuck.. any idea for this problem?
I just want to insert string 2011-03-29 into a SQL Server datetime column using a stored procedure from PHP. I'm sorry because I can't speak English fluently
Whenever I've had a problem like this (using mysql), I just had to add the time (midnight) onto the date so that it can recognize it as the datetime that it's expecting. Try this:
$date = '2011-03-29';
$date .= ' 00:00:00';
Then process the rest as you would. This works for mysql, maybe sql-server needs it like this too.
i got answer from my friends,
just put
mssql_bind($query, "#date", &$date, SQLCHAR); //not sqlint4 for datetime but just sqlchar or sqlvarchar
however many thanks to Groovetrain, i can put also
$date='2011-03-29 00:00:00'
then put
mssql_bind($query, "#date", &$date, SQLCHAR,false,false,19); //19 length of date string
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