SQLSTATE [42000]:语法错误或访问冲突:1064

时间:2013-10-29 20:46:31

标签: php mysql sql pdo

此查询是否有效,如果不能,我怎么能在PHP中使用PDO将查询放入另一个查询?

这是我的问题:

$userid = array($users->school_name_from_id($_SESSION['user_id']), $_SESSION['user_id'], $_SESSION['user_id']);
$statementString =
  'SELECT * FROM schoolinfo 
   WHERE schoolinfo.school = ? AND 
     SELECT count(*) FROM friendstable 
       WHERE friendstable.user_ID = ? 
        AND frienstable.friend_ID = schoolinfo.id  <= 0
   AND 
     SELECT count(*) FROM friendstable 
     WHERE friendstable.user_ID = schoolinfo.id 
       AND friendstable.friend_ID = ?  <= 0 
   ORDER BY RAND()
   LIMIT 6';


        $stmt = $database->_link->prepare($statementString);
        $stmt->execute($userid);
        $array = $stmt->fetchAll(PDO::FETCH_ASSOC);
        print_r($array);

以下是运行时遇到的完整错误:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT count(*) FROM friendstable WHERE friendstable.user_ID = '1' AND frienstab' at line 1' in C:\xampp\htdocs\thinkaztech\PHP\getSocialInformation.php:20 Stack trace: #0 C:\xampp\htdocs\thinkaztech\PHP\getSocialInformation.php(20): PDOStatement->execute(Array) #1 {main} thrown in C:\xampp\htdocs\thinkaztech\PHP\getSocialInformation.php on line 20

1 个答案:

答案 0 :(得分:1)

子查询必须放在括号内:

SELECT   *
FROM     schoolinfo
WHERE    schoolinfo.school = ?
     AND (
           SELECT COUNT(*)
           FROM   friendstable
           WHERE  friendstable.user_ID   = ?
              AND friendstable.friend_ID = schoolinfo.id
         ) <= 0
     AND (
           SELECT COUNT(*)
           FROM   friendstable
           WHERE  friendstable.user_ID   = schoolinfo.id
              AND friendstable.friend_ID = ?
         ) <= 0
ORDER BY RAND()
LIMIT    6

请注意,在这种情况下,您必须将两元素数组传递给PDO::execute()方法:

$stmt->execute([$userid, $userid]);

您可能还会发现,从数据库中获取所需结果的方法要比使用这些相关子查询更有效。