0

在我插入 where 语句之前,我的错误给出了 1064 它工作。我把 where 放在 from 之前还是之后?

<?PHP
session_start();

include ("connection.php");

$city = $_POST['city'];

$state = $_POST['state'];

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

echo json_encode($results);
?>
4

2 回答 2

1
"SELECT business_id, BusinessName, date, post ".
"FROM WolfeboroC.posts ". "WHERE city= '$city' && state='$state'".
"JOIN WolfeboroC.users ON users.recid = posts.business_id ".
"ORDER BY date DESC LIMIT 0, 500"

应该

"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"

JOIN 动词应该在 WHERE 之前。

于 2013-10-21T03:28:05.163 回答
0

您的JOIN WolfeboroC.users语法前面没有空格,因此MySQL.

你的代码:

if( $query =  $db->query("SELECT business_id, BusinessName, date, post ".
  "FROM WolfeboroC.posts ". "WHERE city= '$city' && state='$state'".
  "JOIN WolfeboroC.users ON users.recid = posts.business_id ".
  "ORDER BY date DESC LIMIT 0, 500") ) 

更正的代码:

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' && state='$state' ". "ORDER BY date DESC LIMIT 0, 500") )

此外,您正在选择字段:business_id, BusinessName, date, post.

这些字段是模棱两可的。

您正在加入两个表。

因此,您应该指定哪个字段来自哪个表。

例如users.business_id, users.BusinessName, posts.date, posts.post

在这里,MySQL必须猜测哪个字段属于哪个表。

如果两个表都存在一个字段,则应该引发错误。

此外,在 SQL 中,WolfeboroC.users

您不应指定数据库名称。

它应该只是“用户”。

由于大多数站点的数据库名称是可配置的,因此它会更改。

于 2013-10-21T03:40:20.180 回答