开发者

PHP SQLi Newbie Problem. Fetch not returning True

I am a super newbie php person. Just started scripting a week ago. I have this problem with a function not returning true, even though the data seems to be correct. I’ve spent a day+ searching around for answers.

Here is the abbreviated class.

public function verifyPost()
{
 try
 {
  if(!$this->verifyDatabase())
    throw new Exception('Invalid Username Password');

  $this->access = 1;
 }
 catch(Exception $e)
 {
  $this->errors[] = $e->getMessage();
 }
}

public function verifySession()
{
 if($this->sessionExist() && $this->verifyDatabase())
    $this->access = 1;
}

public function verifyDatabase() 
{
 /* connect to db */ 
 $mysqli = new mysqli ("localhost", "user", "password", "world");  

 /* check connection */ 
 if (mysqli_connect_errno()) { 
        printf("Connect failed: %s\n", mysqli_connect_error()); 
        exit(); 
 } 

 /* create prepare statement */ 
 $stmt = $mysqli->prepare("SELECT ID FROM user WHERE id1 = ? AND id2 = ?"); 
 $stmt->bind_param('ss', $this->id1, $this->id2); 

 /* execute prepared statement */ 
 $stmt->execute(); 

 /* bind variables to prepared statement */ 
 $stmt->bind_result($col1); 

 /* check u开发者_开发技巧ser info in db and assign returned ID to variable*/ 
 if(($stmt->fetch()) != 0) {
        $this->userid = $col1; 
        return true;
 } else {
        return false;
 }

 /* close statement and connection */ 
 $stmt->close(); 

 /* close connection */ 
 $mysqli->close();
}

(I didn't put in the real DB connection info)

For some reason, $access isn’t getting set in verifySession() bc verifyDatabase() doesn’t return true. VerifyDatabase() runs through fine. It finds the User/Pass in the Db and doesn’t throw up the exception. The problem occurs at the IF statement. I’ve isolated the it here by commenting out the whole IF statement except for “return true;” and verifySession() sets $access to 1.

Now I thought it might have been fetch(), so I tried an num_rows() instead and still doesn’t return true.

I hope that makes sense. Let me know if i need to elaborate more. Any help is much appreciated!! Thank you!


$stmt->fetch can return three values, TRUE, FALSE and NULL.

TRUE = Success and data was fetched FALSE = An error occured NULL = No more rows/data exists or data truncation occurred

You should be using the triple = operator which enforces type checking aswell, eg.

if($stmt->fetch() === true) {
  $this->userid = $col1; 
  return true;
} else
  return false;

Or, since this FALSE and NULL will never evaluate to true, you could just write

if($stmt->fetch()) {
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜