1

I have this mysqli prepared statement in PHP

if (isset($_POST['u']) && isset($_POST['p'])) {
    $username = $_POST['u'];
    $password = $_POST['p'];

    $stmt = $conn->stmt_init();
    $stmt = $conn->prepare("SELECT id FROM users WHERE username=? AND password=?");
    $stmt->bind_param("ss",$username,$password);
    $stmt->execute();
    $stmt->store_result();
    $stmt->bind_result($uid);
    if ($stmt->num_rows > 0) {
        $_SESSION["login"] = 1;
        $_SESSION["uid"] = $uid;
        echo $uid;
    }

    $stmt->close();
}

It is echoing "0" when it should show 2, as I am logging into the account whose user id is 2. I have tested the statement with phpMyAdmin, and it is properly returning the correct user id number.

Any help would be awesome and educational, thanks.

BTW I know I am vulnerable to SQL Injections here. I will fix that after I figure this out.

JohnWick
  • 4,929
  • 9
  • 37
  • 74
  • 2
    `->bind_result()` columns are updated only after `->fetch()`. The `->store_result()` is just a caching thing IIRC. Also, no, bound params aren't susceptible to SQL injections. But read up on password hashing in place of storing them raw. – mario Jun 13 '15 at 06:36
  • Hi mario, if you had posted this as an answer I would mark it as the solution thanks. I added $stmt->fetch(); after $stmt->bind_result, then when I echo'd $uid it was the proper userid. You are a life saver. PS I will add password hashing with a salt very soon, probably tomorrow. It's interesting this script isn't vulnerable to SQLi since I did not escape the POST data. I guess with prepared statements I never have to escape the form data? – JohnWick Jun 13 '15 at 06:40
  • 1
    Parameter binding makes escaping mostly obsolete. You could still validate string formats however when feasible. -- Didn't put this in as answer as it's too short. And I don't really want to endorse people using the tedious mysqli API either, ha. - Instead I'd rather link this to [Example of how to use bind\_result vs get\_result](http://stackoverflow.com/q/18753262) which explains it better (likely more useful to future users, and both questions become easier to find if dupe-connected). – mario Jun 13 '15 at 07:11

0 Answers0