简体   繁体   中英

How can I check if a row is empty in mySQL using PDO?

This is how I would normally check for empty results: mysql_fetch_assoc

However, I am using PDO for a client and in this login function, I want to return some text or a number or boolean to say a row was found or not.

public function Login ($email,$password)
{
  $sqlQuery="SELECT * FROM db_user WHERE email= '".$email."'  AND password='".$password." '";
  $statement = $this->_dbHandle->prepare($sqlQuery); // prepare a PDO statement
  $statement -> execute();

  $dataSet= [];
  if(mysql_num_rows($statement) == 1){
    echo 'login true';
  } else {
    echo 'login false';
  }

Both other answers are essentially unacceptable.
And not because they lack cleanness but because they are awfully dangerous

public function Login ($email,$password)
{
  $sql="SELECT 1 FROM db_user WHERE email=?  AND password=?";
  $stmt = $this->_dbHandle->prepare($sql);
  $statement -> execute([$email, $password]);
  return $stmt->fetchColumn();
}

You should be using prepared statements, not just mimicking them.

  $sqlQuery="SELECT * FROM db_user WHERE email= '".$email."'  AND password='".$password." '";
  $statement = $this->_dbHandle->prepare($sqlQuery); // prepare a PDO statement
  $statement -> execute();
  $rows = $statement ->fetch(PDO::FETCH_ASSOC);

  if( ! $rows)
  {
    die('Empty Records');
  }
  $sqlQuery= "SELECT * FROM db_user WHERE email= ? AND password= ?";
  $statement = $this->_dbHandle->prepare($sqlQuery); // prepare a PDO

  // pass parameter to tackle [SQL Injection][1]
  $stmt->execute(array($email, $password)); 

  $result = $stmt->fetch();
  if( $result ) {
      echo "login true";
  }else{
      echo "login false";
  }   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM