Mysql语句在直接运行时有效但在我的php文件中没有

时间:2013-10-26 04:48:48

标签: php mysql

当我在mysql workbench中运行此代码时,它可以工作,但在我的php中它只返回一个空数组。

<?PHP
session_start();

$results = array();
if( $query =  $db->query("SELECT business_id, BusinessName, date, post ".
  "FROM WolfeboroC.posts ".
  "JOIN WolfeboroC.users ON users.recid = posts.business_id ".
  "WHERE City= '$city' AND State='$state'".
  "ORDER BY date DESC LIMIT 0, 500") ) 
{
  while($record = $query->fetch_assoc())
  {
    $results[] = $record;
  }
  $query->close();
}

echo json_encode($results);
?>

1 个答案:

答案 0 :(得分:0)

首先,你不能使用结构

FROM
WHERE
JOIN

你必须使用

FROM
JOIN
WHERE

其次,您在'$state'"

的末尾错过了一个空格
"FROM WolfeboroC.posts ". "WHERE city= '$city' && state='$state'".
"JOIN WolfeboroC.users ON users.recid = posts.business_id ".

所以我很确定,正如你所提到的那样,它并不适用于MySQL。

还有一些PHP错误。使用此代码:

if($result = $db->query(
  "SELECT business_id, BusinessName, date, post ".
  "FROM WolfeboroC.posts ".
  "JOIN WolfeboroC.users ON users.recid = posts.business_id ".
  "WHERE City= '$city' AND State='$state' ".
  "ORDER BY date DESC LIMIT 0, 500")) {
  while($record = $result->fetch_assoc()) {
    $results[] = $record;
  }
  $result->close();
}