-1

我正在尝试解决我在使用登录表单时遇到的问题。我已经发布了基本的 html 表单,然后是我正在使用的 php 脚本。每次我尝试登录它都不起作用。

Html - 用户名: 密码:   

php -

$link = mysqli_connect('host', 'db', 'pw', 'db');
$login = mysqli_query($link, "SELECT * FROM users WHERE (username = '" .($_POST[username]) . "') and (password = '" .($_POST[password]) . "')");

if (mysql_num_rows($login) == 1) {
$_SESSION[username] = $_POST[username];
header('Location: adminpage.php');
}
else {
header('Location: login.html');
}
?>

任何帮助将非常感激。谢谢

4

3 回答 3

3

使用以下代码更改 php 代码:-

session_start();

$link = mysqli_connect('host', 'db', 'pw', 'db');
$username = $_POST['username'];
$password = $_POST['password'];
$login = mysqli_query($link, "SELECT * FROM users WHERE username = '$username' AND  password = '$password'");

if (mysql_num_rows($login) == 1) {
    $_SESSION['username'] = $username;
    header('Location: adminpage.php');
}
else {
    header('Location: login.html');
}
于 2013-05-02T05:35:05.177 回答
0

您需要在 $_POST 和 $_SESSION 变量周围加上引号:

$_POST['username']
$_SESSION['username']

此外,您必须使用mysqli_num_rows,因为您正在使用mysqli. (不只是mysql_num_rows

并确保您阅读了有关防止 SQL 注入的内容。如果您在将这些 $_POST 变量插入 SQL 查询之前不清理它们,那么有人可能很容易侵入您的数据库。

我进行了以下更改:


// Make sure to replace the 4 parameters in the next line with your actual database info.
$link = mysqli_connect('THE_URL_TO_YOUR_DATABASE', 'YOUR_USERNAME', 'YOUR_PASSWORD', 'YOUR_DATABASE_NAME');
$login = mysqli_query($link, "SELECT * FROM users WHERE (username = '" .$_POST['username'] . "') and (password = '" .$_POST['password'] . "')");

if (mysqli_num_rows($login) == 1) {
    $_SESSION['username'] = $_POST['username'];
    header('Location: adminpage.php');
} else {
    header('Location: login.html');
}
于 2013-05-02T05:30:05.527 回答
0

在执行任务之前始终进行错误检查

session_start();

$link = mysqli_connect('host', 'un', 'pw', 'db');
// Check connection
if (mysqli_connect_errno($link))
{
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

// Perform a query, check for error
$user = $_POST['username'];
$pswd = $_POST['password'];
$login = mysqli_query($link, "SELECT * FROM users WHERE (username = '$user') and (password = '$pswd')");

if (mysql_num_rows($login) == 1) {
      $_SESSION['username'] = $user;
      header('Location: adminpage.php');    
}else {
    echo("Error description: " . mysqli_error($link));
}
于 2013-05-02T05:53:08.870 回答