2

I have a function as below to extract records from mysql database.

function getMember($read, $selected_joined_date) {
  $sql = "SELECT first_name, last_name, member.joined_date
          FROM user 
          INNER JOIN member USING (user_id)
          WHERE user.joined_date > $selected_joined_date
          ORDER BY joined_date";
  return $read->fetchAll($sql);
}

It dipslays error message displayed as

'SQLSTATE[42000]: Syntax error or access violation.

The field 'joined_date' is datetime format in table and $selected_joined_date is string format.

How do I compare the different type of datetime format ?

peterm
  • 91,357
  • 15
  • 148
  • 157
user2359714
  • 21
  • 1
  • 2

4 Answers4

1

You need quotes around your strings in your query.

$sql = "SELECT first_name, last_name, member.joined_date
        FROM user 
        INNER JOIN member USING (user_id)
        WHERE user.joined_date > '$selected_joined_date'
        ORDER BY joined_date";
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
0

You can use Date() function provided by mysql to convert string format to Date

 mysql> SELECT DATE('2003-12-31 01:02:03');
        -> '2003-12-31'

And your query will look like: Got MySql Solution, you can use str_to_date function as;

 mysql>select str_to_date('2012-10-12 10:20:30','%Y-%m-%d %H:%i:%s');

So your Sql String will be,

$sql = "SELECT first_name, last_name, member.joined_date
      FROM user 
      INNER JOIN member USING (user_id)
      WHERE user.joined_date >str_to_date('$selected_joined_date','%Y-%m-%d %H:%i:%s')
      ORDER BY joined_date";
// Provided that string selected_joined_date is in format 2012-10-12 10:20:30
progrrammer
  • 4,475
  • 2
  • 30
  • 38
0

Mysql likes datetimes in the format "2013-05-07 15:30:00", php can handle just about anything.

You would convert $selected_join_date to that format like so:

$selected_join_date = date("Y-m-d H:i:s", strtotime($selected_join_date));

assuming $selected_join_date is in one of php's accepted formats: http://www.php.net/manual/en/datetime.formats.php

Then you can pass the string to mysql and it will happily compare them. The variable (and therefore the string date time) needs to be inside quotes in the sql, as Rocket Hazmat pointed out.

TrippyD
  • 735
  • 5
  • 9
0

I made a little test out of curiosity whether php date format must be the same as mysql datetime format. It turned out that format does not matter. If a PHP variable was in Mysql Date and Time format, search was successful.

default mysql datetime format:

YYYY-MM-DD HH:MM:SS

formats used for searching database:

'Y-m-d H:i:s'
'Y/m/d H:i:s'
'Y/m/d'
'YmdHis'
'Ymd'

date formatted with DateTime::createFromFormat() function

The problem, except that $selected_joined_date variable in query needs to be inside quotes, seems to be elsewhere.

Danijel
  • 12,408
  • 5
  • 38
  • 54