将mysql转换为PDO语句

时间:2012-02-03 09:30:48

标签: php mysql pdo

这是使用MySQL方式编写的登录功能 但是,当它转换为PDO方式时存在问题

MYSQL:

    <?
function confirmUser($username, $password){
   global $conn;
   if(!get_magic_quotes_gpc()) {
    $username = addslashes($username);
   }

   /* Verify that user is in database */
   $q = "select UserID,UserPW from user where UserID  = '$username'";
   $result = mysql_query($q,$conn);
   if(!$result || (mysql_numrows($result) < 1)){
      return 1; //Indicates username failure
   }

   /* Retrieve password from result, strip slashes */
   $dbarray = mysql_fetch_array($result);
   $dbarray['UserPW']  = stripslashes($dbarray['UserPW']);
   $password = stripslashes($password);

   /* Validate that password is correct */
   if($password == $dbarray['UserPW']){
      return 0; //Success! Username and password confirmed
   }
   else{
      return 2; //Indicates password failure
   }
}

PDO:

<?
function confirmUser($username, $password){
   global $conn;

   include("connection/conn.php");

   $sql = '
    SELECT   COALESCE(id,0) is_row
    FROM     user
    WHERE    UserID = ?
    LIMIT 1
';

$stmt = $conn->prepare($sql);
$stmt->execute(array('09185346d'));
$row = $stmt->fetch();

if ($row[0] > 0) {
       $sql = '
    SELECT   COALESCE(id,1) is_row
    FROM     user
    WHERE    UserPW = ?
    LIMIT 1
';
$stmt = $conn->prepare($sql);
$stmt->execute(array('asdasdsa'));
$row = $stmt->fetch();
    if ($row[0] > 0) 
    return 2;
    else
    return 0;
}
elseif ($row[0] = 0)
{return 1;}   



}

问题是什么?是否有必要在PDO中包含绑定参数?致谢

1 个答案:

答案 0 :(得分:1)

除了在函数内使用globalinclude之外(你应该研究一种构造函数的替代方法,不要这样做),我会改变代码如下:

$sql =
    'SELECT  id
    FROM     user
    WHERE    UserID = ?
    AND      UserPW = ?
    LIMIT 1';

$stmt = $conn->prepare($sql);
$stmt->execute(array(
    '09185346d',
    'asdasdsa'
));

if ($stmt->rowCount() == 1) {
    return 0;
}
else {
    return 1;
}

组合查询以提供常规身份验证错误,而不是允许人们尝试有效的用户名,然后使用有效的密码,然后使用PDOStatements rowCount方法查看您的行是否已返回。

要回答第二部分,没有必要专门使用bindParam来阻止SQL注入。

以下是bindParambindValue

之间差异的快速示例
$param = 1;

$sql = 'SELECT id FROM myTable WHERE myValue = :param';
$stmt = $conn->prepare($sql);

使用bindParam

$stmt->bindParam(':param', $param);
$param = 2;
$stmt->execute();

SELECT id FROM myTable WHERE myValue = '2'

使用bindValue

$stmt->bindValue(':param', $param);
$param = 2;
$stmt->execute();

SELECT id FROM myTable WHERE myValue = '1'