Mysql语法似乎是正确的,但提供错误代码1064

时间:2013-10-21 03:16:16

标签: php mysql

在插入where语句之前,我的错误给出了1064。我把它放在之前或之后的地方吗?

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

2 个答案:

答案 0 :(得分: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之前。

答案 1 :(得分: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'&amp;&amp;状态=“$状态” ”。       “ORDER BY date DESC LIMIT 0,500”))

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

这些领域是暧昧的。

你要加入两张桌子。

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

e.g。 users.business_id, users.BusinessName, posts.date, posts.post

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

如果两个表都存在字段,则应该抛出错误。

此外,在SQL中,WolfeboroC.users

您不应指定数据库名称。

它应该只是“用户”。

由于数据库名称可以为大多数网站配置,因此会发生变化。