0

I an having a tough time with this and trying to either return 1 or true if my select statement finds a record. I am working with MSSQL Server and PHP with PDO because of its safety. I know that fetchColumn() is not the right statement to use, but that's where I gave up because I tried almost everything else.

Here is my code.

public function activate($email, $email_code) {
        $query = $this->db->prepare("SELECT * FROM users WHERE (email = ? AND email_code = ? AND confirmed = ?)");

        $query->bindValue(1, $email);
        $query->bindValue(2, $email_code);
        $query->bindValue(3, 0);

        try{

            $query->execute();
            $rows = $query->fetchColumn();// HERE I AM NOT SURE WHAT TO USE ??? HELP!
            if($rows == 1){


                $query_2 = $this->db->prepare("UPDATE users SET confirmed =? WHERE email = ?");
                $query_2->bindValue(1, 1);
                $query_2->bindValue(2, $email);             

                $query_2->execute();
                return true;

            }else{
                return false;
            }

        } 
            catch(PDOException $e){
            die($e->getMessage());
        }

    }
4

1 回答 1

1

您当前代码的问题(除了在参数占位符周围使用引号)是fetchColumn()让您获得结果集中第一列的值,这可能是某种 id 并且该值不等于 1。这就是为什么你总是变得虚假。

你可以通过使用rowCount()而不是解决这个问题fetchColumn()

$rows = $query->rowCount();

现在,要检查是否存在行,您不需要实际检索所有列的结果集。只需使用COUNT(*). 它会返回一行,一列,后面的值是你得到的fetchColumn()

尝试改变

$query = $this->db->prepare("SELECT * FROM users WHERE (email = ? AND email_code = ? AND confirmed = ?)");

$query = $this->db->prepare("SELECT COUNT(*) FROM users WHERE (email = ? AND email_code = ? AND confirmed = ?)");

if($rows == 1){

to (只是为了安全,如果由于某种原因有重复)

if($rows > 0) {

更新

由于rowCount()返回受UPDATE函数更简洁版本影响的行数可能如下所示

public function activate($email, $email_code) {
    $sql = 'UPDATE users 
              SET confirmed = 1 
            WHERE email = ?
              AND email_code = ?
              AND confirmed = 0';

    $rows = 0;

    try{
        $query = $this->db->prepare($sql);

        $query->bindValue(1, $email);
        $query->bindValue(2, $email_code);

        $query->execute();
        $rows = $query->rowCount();
        $query = null;
    } catch(PDOException $e) {
        die($e->getMessage());
    }
    return ($rows > 0);
}

注意:您不需要为列绑定0静态值1confirmed

于 2013-06-14T02:49:02.827 回答