将FROM_UNIXTIME添加到WHERE子句时出现未知的PHP PDO错误

将FROM_UNIXTIME添加到WHERE子句时出现未知的PHP PDO错误

问题描述:

I have this code and I'm not sure why it isn't working. Apparently it is not catching any exceptions, I tried to debug and found out that it is breaking at the point where i add:

WHERE MONTH(FROM_UNIXTIME(unixtime))='7'

Because when I remove that, everything seem to work just fine.

<?php
try {
  $dbh = new PDO('mysql:host=localhost;dbname=myDb', 'root', 'password');
  $dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

  $stmt = $dbh->prepare('SELECT col1, count(*) as frequency FROM myTable WHERE MONTH(FROM_UNIXTIME(unixtime))='7' GROUP BY col1 ORDER BY frequency DESC');
  $stmt->execute();

  // populate results
  $results = array();
  foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
    $row_array['col1'] = $row['col1'];
    $row_array['frequency'] = $row['frequency'];

    array_push($results,$row_array);      
  }

  // and return to typeahead
  echo json_encode($results);           


  $dbh = null;
} catch (PDOException $e) {
  print "Error!: " . $e->getMessage() . "<br/>";
  die();    
}
?>

I would also appreciate any help about enabling error logs to show up, if any php.ini or other server configuration has to be edited or configured please let me know.

Thanks!

You have a problem with quotations. do like this

$stmt = $dbh->prepare("SELECT col1, count(*) as frequency 
 FROM myTable 
   WHERE MONTH(FROM_UNIXTIME(unixtime))='7' GROUP BY col1 ORDER BY frequency DESC");

Change the single quotes around the SQL statement in double quotes. The single quotes around the 7 causes your problem. Single quotes within single quotes.