0

I've gone through quite a number of stackoverflow threads and I simply can't get it right to retrieve the results after preparing a query. I've tried a number of different solutions and none seem to be able to fetch the associative array after I execute the query

    $mysqli = new MySQLi('localhost', 'root', '', 'prac2');
    $query = $mysqli-> prepare("SELECT * FROM `user` WHERE username=? and password=?");
    $query-> bind_param('ii', $username, $password);
    if($query-> execute())  {
        $query->store_result();
        if ($query -> num_rows > 0) {
            $result = $mysqli->query($query);
            $r = $result -> fetch_array(MYSQLI_ASSOC)['userid'];
            $_SESSION['userid'] = $r;
        }
    }

I've established that sometimes its a case of result containing a boolean for success but I'm still not certain what exactly I'm doing wrong.

UPDATED:

Okay the bind_param works now, but the fetch_assoc keeps giving me the error "Call to a member function fetch_assoc() on a non-object", I even test the result to ensure that it returns true.

$mysqli = new MySQLi('localhost', 'root', '', 'prac2');
$query = $mysqli->prepare("SELECT * FROM user WHERE username=? and password=?");
echo $mysqli->error;
$query-> bind_param('ss', $username, $password);
if($query->execute())  {
    $result = $query -> store_result();
    if($result) {
        while($row = $result -> fetch_assoc()){
            echo $row['userid'];
            $_SESSION['userid'] = $row['userid'];
        }
    }
}
  • why is bind_param ii? try ss – Aleksandar Vasić Sep 01 '14 at 10:40
  • @Aleksandar as I mentioned I went through quite a number of different articles and for the most part I'm quite confused. 'ss' givs me the same errors: "mysqli::query() expects parameter 1 to be string" and "Call to a member function fetch_array() on a non-object" – Chris Crossman Sep 01 '14 at 10:44
  • Call to a member function fetch_array() on a non-object, happens when your query isnt good, change ii to ss, and check what are you getting in your $username and $password variables – Aleksandar Vasić Sep 01 '14 at 10:46

2 Answers2

2

Usernames and password are strings and it should be 's' denoting that corresponding variable has type string. I don't see how usernames and passwords are integers. Bind Param Types

   $query-> bind_param('ss', $username, $password);
John Robertson
  • 1,486
  • 13
  • 16
0

Inside bind_param for string you should use s. I mean try ss instead of ii.

David Bohunek
  • 3,181
  • 1
  • 21
  • 26