-2

So I'm trying to update some stuff in my database when the user logs on, it seems that everything is fine except the last part, the output I am getting is:

"critical error unknown" and "Commands out of sync; you can't run this command now"

Here is my code:

<?php
$user = $_POST['username'];
$pass = $_POST['password'];
$connect = mysqli_connect("localhost","myuser","mypass","somedb");
$query = "SELECT `password` FROM `userauth` WHERE `username`=?";
if($stmt = $connect->prepare($query)){
    $stmt->bind_param('s',$user);
    $stmt->execute();
    $stmt->bind_result($tmp_pass);
    $stmt->fetch();
    if($tmp_pass===$pass){
        $letters = array('a','b','*','x','e','d','z','p','@','#');
        $letter_key="";
        for($i=0;$i<sizeof($letters);$i++){
            $letter_key=$letter_key.$letters[rand(1,sizeof($letters-1))];
        }
        $key = rand(1341163,9999999);
        $key2 = rand(3541,9999);
        $complete_key = $key.$letter_key.$key2;
        setcookie("key",$complete_key);
        setcookie("user",$user);
        $query_auth = "UPDATE `userauth` SET `auth_key`=? WHERE `username`=?";
        if($stmt_2 = $connect->prepare($query_auth)){
            $stmt_2->bind_param('ss',$complete_key,$user);
            $stmt_2->execute();
        }else{
            echo "Critical error, unknown ".mysqli_error($connect);
            exit;
        }
        echo "success";
    }else{
        echo "Error Invalid Username or Password";
    }
}else{
    "Database link error";
}
?>

Can someone please explain what might be the problem. yes, all my fields are string.

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
Talha Tanveer
  • 1,196
  • 8
  • 16

1 Answers1

2

Try $stmt->close() after $stmt->fetch()

  • it works, I'll accept your answer as I have to wait 5 minutes. Can you explain it please? – Talha Tanveer Aug 12 '14 at 17:58
  • 1
    Here is a good explanation from php.net: "Closes a prepared statement. mysqli_stmt_close() also deallocates the statement handle. If the current statement has pending or unread results, this function cancels them so that the next query can be executed." –  Aug 12 '14 at 18:01
  • 1
    Link [http://php.net/manual/en/mysqli-stmt.close.php](http://php.net/manual/en/mysqli-stmt.close.php) –  Aug 12 '14 at 18:02