Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zend Framework - counting rows in select clause?

I'm investigating Zend Framework and currently stucked in counting resulting rows of sql query... Every method I try (from documentation and some blogposts and tutorials) returns an error (like Call to undefined function) or simply gives the incorrect value.

I've tried this:

$checkquery = $db->select()
   ->from('users', 'COUNT(*)')
   ->where('login = ?', $login)
   ->where('password = ?', $password)
   ->query();

$checkrequest=fetchRow($checkquery)->num;

...then this one:

$checkquery = $db->select()
   ->from('users', '*')
   ->where('login = ?', $login)
   ->where('password = ?', $password)
   ->query();

$checkrequest=count($checkquery->fetchAll());

and even:

$checkquery = $db->select()
   ->from('users', '*')
   ->where('login = ?', $login)
   ->where('password = ?', $password)
   ->query();

$checkrequest=$checkquery->fetchAll()->num;

Also rowCount() and count(fetchRow()) and count(fetchAll()->toArray()). But always I got an error message or duplicate inserts in db in further insert function. So what is the correct way to do the resulting row calculation in select clause in Zend Framework 1.9 (I use this one) ?

like image 492
moogeek Avatar asked Jun 01 '10 20:06

moogeek


1 Answers

The usage you're trying to do is as follows:

$checkquery = $db->select()
   ->from("users", array("num"=>"COUNT(*)"))
   ->where("login = ?", $login)
   ->where("password = ?", $password);

$checkrequest = $db->fetchRow($checkquery);
echo $checkrequest["num"];

I have a couple of other tips:

  • Your query doesn't distinguish between login not found and incorrect password.
  • Your passwords may be stored in plain text, which is a security risk. You should use a one-way hash function and salting.

I would restructure the query like this:

$checkquery = $db->select()
   ->from("users", array("pwd_is_correct"=>
     $db->quoteInto("(password = SHA1(CONCAT(salt, ?)))", $password)))
   ->where("login = ?", $login);

$checkrequest = $db->fetchRow($checkquery);
if ($checkrequest === false) {
  echo "no such login\n";
} else if ($checkrequest["pwd_is_correct"] > 0) {
  echo "login and password are correct\n";
} else {
  echo "login found but password is incorrect\n";
}

You don't have to report the different cases to the user -- in fact it's best security practice not to tell them which of the login or password is incorrect. But you might want to know in your own code so you can lock out an account that's receiving a lot of failed passwords.

SHA1() is not as good as SHA2() which is available in MySQL 5.5 and later.

like image 53
Bill Karwin Avatar answered Nov 02 '22 05:11

Bill Karwin