0

我有点困惑,因为当尝试下面的代码时,我收到了想要的结果。

   include_once('config.class.php');
   $db = Core::getInstance();     
   $whr = 'test@nannex.com';

  $inv = $db->dbh->prepare("SELECT * FROM ruj_users WHERE email=:whr");
  $inv->execute(array(":whr"=>$whr));
  $row = $inv->fetch(PDO::FETCH_ASSOC);
    echo $row['email'];
    echo $row['full_name'];

但是,当我运行以下代码时,它返回 1 而不是所需的结果。

     include_once('config.class.php');
     $db = Core::getInstance();     
     $whr = 'test@nannex.com';    

     function fetchUser($whr){  
    $db = Core::getInstance();              
    $inv = $db->dbh->prepare("SELECT * FROM ruj_users WHERE :whr");
            $inv->execute(array(':whr'=>$whr)); 
    $res = $inv->fetch(PDO::FETCH_ASSOC);
    return $res;
}
    $row = fetchUser("email = '".$whr."' "); 
    echo $row['email'];
    echo $row['full_name'];
4

2 回答 2

1

您在函数中的查询中有错误:

$inv = $db->dbh->prepare("SELECT * FROM ruj_users WHERE :whr");

应该:

$inv = $db->dbh->prepare("SELECT * FROM ruj_users WHERE email=:whr");

编辑:如果您还想传递列名,则必须向函数添加另一个变量:

function fetchUser($column, $value) {

请注意,只有值可以绑定在准备好的语句中,您必须对照白名单检查列变量以避免查询中的 sql 注入和硬代码,例如... WHERE $column = :whr ...

于 2012-12-11T23:53:49.747 回答
1

这个查询:

SELECT * FROM ruj_users WHERE :whr

展开时:

SELECT * FROM ruj_users WHERE 'email = \'test@nannex.com\''

该表达式email = \'test@nannex.com\'将由 MySQL 评估为布尔值,并且始终为真,因此它将返回ruj_users.

如果你想要自定义条件,你可以这样做:

function fetchUser(array $conditions)
{
    // ...
    $sql = 'SELECT * FORM ruj_users WHERE';
    $params = array();
    foreach ($conditions as $column => $value) {
        if (preg_match('/^[a-z]+$/', $column)) {
            $sql .= "`$column` = ?";
            $params[] = $value;
        }
    }
    $inv = $db->dbh->prepare($sql);
    $inv->execute(array_values($params));
    // ...
}

fetchUser(array(
    'email' => 'test@nannex.com',
    'status' => 23,
));
于 2012-12-11T23:56:13.307 回答