I'm trying to convert my code for querying and accessing user login info and putting into session varibles to using a prepared statement to do the same thing, but I can't figure it out.
Original:
$query = "SELECT id FROM customer WHERE username='$username' AND password='$password' LIMIT 1";
$result = $db_obj->query($query);
if($db_obj->error) exit ($db_obj->error);
$login_check = $result->num_rows;
if($login_check == 1){
while($row = $result->fetch_array(MYSQLI_ASSOC)){
// Get member ID into a session variable
$id = $row["id"];
}
$_SESSION['id'] = $id;
// Get member username into a session variable
$_SESSION['username'] = $username;
// Print success message here if all went well then exit the script
//header("location: index.php?id=$id");
header("location: index.php");
exit();
// close while
} else {
// Print login failure message to the user and link them back to your login page
print '<br /><br /><font color="#FF0000">No match in our records, try again </font><br />
<br /><a href="user_login.php">Click here</a> to go back to the login page.';
exit();
}
Code trying to use prepared statement:
$stmt = $db_obj->stmt_init();
if($stmt->prepare("SELECT `id`FROM `customer` WHERE `username` = ? AND pass = ? LIMIT 1")) {
$stmt->bind_param($username, $password);
$stmt->execute();
$stmt->bind_result($username, $password);
if ($stmt->fetch()){
while($row = $result->fetch_array(MYSQLI_ASSOC)){
// Get member ID into a session variable
$id = $row["id"];
}
$_SESSION['id'] = $id;
// Get member username into a session variable
$_SESSION['username'] = $username;
// Print success message here if all went well then exit the script
//header("location: index.php?id=$id");
header("location: index.php");
exit();
// close while
} else {
// Print login failure message to the user and link them back to your login page
print '<br /><br /><font color="#FF0000">No match in our records, try again </font><br />
<br /><a href="user_login.php">Click here</a> to go back to the login page.';
exit();
}
I believe my problem is in the while loop and with trying to use fetch(), but I'm not sure how to go about doing it. If someone could help I would appreciate it. Thank you.