php pdo从多个表中选择多个where子句

时间:2013-02-12 18:03:34

标签: php mysql pdo

我是PHP PDO的新手,并将一些常规MySQL查询转换为与PDO一起使用。

当分配的值替换SQL语句中的当前占位符时,在phpMyAdmin中测试时,下面的查询效果很好。但是当我将它配置为现在使用PDO时,它不会产生任何结果或错误。有人可以告诉我或告诉我我做错了什么?

有人告诉我,我不能在数组中传递参数作为参考。

如果正确,创建解决方案的最佳方式是什么,并且只使用传递给变量$uid的用户ID。感谢。

<p>// For testing</p>
<pre>$uid = 1;</pre>
<p>&nbsp;</p>   
<pre>$array = array(
    ':uId' => ''.$uid.'',
    ':aId' => 'u.user_id',
    ':gID' => 'a.group_id',
    ':eID' => 'a.entry_id',
    ':pID' => 'a.permit_id'
    );</pre>

   

//为qd_user_usam表创建sql

    
$sql = "SELECT u.user_id, a.acl_id, g.group_name, e.entry_level, p.permit_level
            
FROM qd_users as u, qd_users_acl as a, qd_users_group as g, qd_users_entry as e, qd_users_permission as p 
            
WHERE u.user_id = :uID
            AND a.acl_id    = :aID 
            AND g.group_id  = :gID
            AND e.entry_id  = :eID
            AND p.permit_id = :pID";

<p>try
{</p>
   <p>// Build the database PDOStatement</p>
   <pre>$_stmt = $this->_dbConn->prepare($sql);</pre>
   <pre>$_stmt->execute($array);</pre>
<pre>}
catch(PDOException $e)
{</pre>
    <pre>$this->_errorMessage .= 'Error processing user login access. <br /> Line #'.__LINE__ .' '.$e ;</pre>  
    <pre>die($this->_errorMessage);
}</pre>

<pre>$results = $_stmt->fetchAll(PDO::FETCH_ASSOC);</pre>
<pre>return $results;</pre>

<pre>$results = null;</pre>
<pre>$this->_dbConn = null;</pre>

2 个答案:

答案 0 :(得分:1)

你准备好的陈述是错误的 您必须使用不代表查询中的任何值,但仅动态添加数据

虽然a.group_id是列名,但必须按原样编写,没有预备语句

// For testing
$uid = 1;

// create the sql for qd_user_usam table
$sql = "SELECT u.user_id, a.acl_id, g.group_name, e.entry_level, p.permit_level 
        FROM qd_users as u, qd_users_acl as a, qd_users_group as 
             g, qd_users_entry as e, qd_users_permission as p 
        WHERE u.user_id = ?
        AND a.acl_id    = u.user_id
        AND g.group_id  = a.group_id
        AND e.entry_id  = a.entry_id
        AND p.permit_id = a.permit_id";
$_stmt = $this->_dbConn->prepare($sql);
$_stmt->execute(array($uid));

答案 1 :(得分:1)

问题是你试图通过将连接列绑定为参数来隐式编写JOIN,这是行不通的。参数不能引用另一列;在这种情况下,它们被视为字符串。如果您像这样重写查询,则应修复JOIN问题:

SELECT u.user_id, a.acl_id, g.group_name, e.entry_level, p.permit_level 
    FROM qd_users AS u
        JOIN qd_users_acl AS a ON (u.user_id = a.acl_id)
        JOIN qd_users_group AS g ON (g.group_id = a.group_id)
        JOIN qd_users_entry AS e ON (e.entry_id = a.entry_id)
        JOIN qd_users_permission AS p ON (p.permit_id = a.permit_id)
    WHERE u.user_id = :uID