login not working when changing from mysql to mysqli
- by user1438647
I have a code below where it logs a teacher in by matching it's username and password in the database, if correct, then log in, if incorrect, then display a message.
<?php
session_start();
$username="xxx";
$password="xxx";
$database="mobile_app";
$link = mysqli_connect('localhost',$username,$password);
mysqli_select_db($link, $database) or die( "Unable to select database");
foreach (array('teacherusername','teacherpassword') as $varname) {
$$varname = (isset($_POST[$varname])) ? $_POST[$varname] : '';
}
?>
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post" id="teachLoginForm">
<p>Username</p><p><input type="text" name="teacherusername" /></p> <!-- Enter Teacher Username-->
<p>Password</p><p><input type="password" name="teacherpassword" /></p> <!-- Enter Teacher Password-->
<p><input id="loginSubmit" type="submit" value="Login" name="submit" /></p>
</form>
<?php
if (isset($_POST['submit'])) {
$query = "
SELECT * FROM Teacher t
WHERE
(t.TeacherUsername = '".mysqli_real_escape_string($teacherusername)."')
AND
(t.TeacherPassword = '".mysqli_real_escape_string($teacherpassword)."')
";
$result = mysqli_query($link, $query);
$num = mysqli_num_rows($result);
$loged = false;
while($row = mysqli_fetch_array($result))
{
if ($_POST['teacherusername'] == ($row['TeacherUsername']) && $_POST['teacherpassword'] == ($row['TeacherPassword']))
{
$loged = true;
}
$_SESSION['teacherforename'] = $row['TeacherForename'];
$_SESSION['teachersurname'] = $row['TeacherSurname'];
$_SESSION['teacherusername'] = $row['TeacherUsername'];
}
if ($loged == true){
header( 'Location: menu.php' ) ;
}else{
echo "The Username or Password that you Entered is not Valid. Try Entering it Again.";
}
mysqli_close($link);
}
?>
Now the problem is that even if the teacher has entered in the correct username and password, it still doesn't let the teacher log in. When the code above was the old mysql() code, it worked fine as teacher was able to login when username and password match, but when trying to change the code into mysqli then it causes login to not work even though username and password match. What am I doing wrong?