views:

221

answers:

1

Hello! 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) ?

+3  A: 

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:

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() but SHA2() is available only in MySQL 5.5 which is currently in development release.

Bill Karwin
Thanks! tho, $password variable is md5 hashed with salt
moogeek