TheBlackBenzKid
TheBlackBenzKid

Reputation: 27087

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';
  }

Upvotes: 0

Views: 604

Answers (3)

6339
6339

Reputation: 475

  $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";
  }   

Upvotes: 0

Your Common Sense
Your Common Sense

Reputation: 157895

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.

Upvotes: 2

Omkar
Omkar

Reputation: 308

  $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');
  }

Upvotes: 0

Related Questions