php用户名和密码检查不起作用

时间:2019-03-14 17:40:09

标签: php mysql apache

我正在尝试使登录页面与php和mysql一起使用,但是它不起作用,我是php的新手。 我想要的是输入正确的用户名和通行证后,显示/回显该用户的级别

mysql:image

db.php:

<?php
$servername = "127.0.0.1";
$username = "root";
$password = "";
$dbname = "maindb";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
# open database like before.
$web_username=$_POST['username'];
if ($web_username=="") die(); # one bit of error handling.
$web_password=$_POST['password'];
$sql = "SELECT id, level FROM users WHERE name = ? AND password = ?";
$stmt =  $conn->prepare ($sql ); # needs error check
$stmt->bind_param("ss", $web_username, $web_password);
$stmt->execute(); # needs error check
if ($stmt->num_rows==1) {
    $stmt->bind_result($id, $level);
    $stmt->fetch(); 
    printf ("id is %s, level is %s\n", $id, $level);
}
?>

index.html:

<html>
<body>
<form method='post' action='db.php'>
Username: <input type='text' name='username' placeholder='username'><br>
Password: <input type='password' name='password' placeholder='password'><br>
<input type="submit" value="Submit" />
</form></body></html>

1 个答案:

答案 0 :(得分:0)

store_result();$stmt->execute();之后添加db.php

因此实际的代码将是

<?php
$servername = "127.0.0.1";
$username = "root";
$password = "";
$dbname = "maindb";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
# open database like before.
$web_username=$_POST['username'];
if ($web_username=="") die(); # one bit of error handling.
$web_password=$_POST['password'];
$sql = "SELECT id, level FROM users WHERE name = ? AND password = ?";
$stmt =  $conn->prepare ($sql ); # needs error check
$stmt->bind_param("ss", $web_username, $web_password);
$stmt->execute(); # needs error check
$stmt->store_result();
if ($stmt->num_rows==1) {
    $stmt->bind_result($id, $level);
    $stmt->fetch(); 
    printf ("id is %s, level is %s\n", $id, $level);
}
?>

这将解决您的问题。