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

时间:2014-10-01 13:05:46

标签: php mysql pdo ubuntu-14.04 php-ini

我有这个代码,我不确定它为什么不起作用。显然它没有捕获任何异常,我试图调试并发现它在我添加的地方突破:

月份(FROM_UNIXTIME(unixtime))='7'

因为当我删除它时,一切似乎都很好。

<?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();    
}
?>

我也很感激有关启用错误日志的任何帮助,如果有任何php.ini或其他服务器配置需要编辑或配置,请告诉我。

谢谢!

2 个答案:

答案 0 :(得分:1)

您的报价有问题。喜欢这个

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

答案 1 :(得分:0)

用双引号更改SQL语句周围的单引号。围绕7的单引号会导致您的问题。单引号内的单引号。