I've got a simple form to register users that works perfectly. Now I'm trying to log in with any registered user but I can't make it work. I've been reading a while about people with the same problem but I can't find a solution.
Here's my code:
connection.inc.php
<?php
$name = 'pruser';
$pwd = 'pruser';
$dbname = 'project1db';
$conn = new mysqli("localhost", $name, $pwd, $dbname);
login.php
<?php
include('connection.inc.php');
if (isset($_POST['login'])) {
session_start();
$username = trim($_POST['user']);
$password = trim(sha1($_POST['pass']));
// check user in db
$sql = "SELECT user, pwd FROM users WHERE user = ? AND pwd = ? LIMIT 1";
$stmt = $conn->prepare($sql);
if ($stmt === false) {
echo 'Error';
}
$stmt->bind_param('ss', $username, $password);
$stmt->execute();
$stmt->bind_result($username, $password);
echo $stmt->num_rows;
$stmt->close();
}
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Log in - Project 1</title>
</head>
<body>
<form id="form1" method="post" action="">
<fieldset>
<legend>Log in</legend>
<p>
<label for="user">Username</label>
<input type="text" name="user" id="user">
<label for="pass">Password</label>
<input type="password" name="pass" id="pass">
</p>
<p>
<input type="submit" name="login" id="login" value="Log in">
</p>
</fieldset>
</form>
<a href="register.php">Register</a/>
</body>
</html>
When I check how many rows are affected the result is -1. After loging in I want it to redirect to index.php. That's not a problem, but first I need to log in.
Try calling $stmt->store_result();
right after $stmt->execute();
$sql = "SELECT count(*) FROM users WHERE user = ? AND pwd = ? LIMIT 1";
$stmt = $conn->prepare($sql);
if ($stmt === false) {
echo 'Error';
}
$stmt->bind_param('ss', $username, $password);
$stmt->execute();
$stmt->bind_result($count);
$stmt->fetch;
$stmt->close();
if($count > 0){
## login OK
} else {
## login false
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.