mysql

92vpleto  于 2021-06-21  发布在  Mysql
关注(0)|答案(3)|浏览(254)

尝试在index.php上显示数据,用户名工作正常,电子邮件没有显示。
服务器.php

$query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 1) {

  $_SESSION['email'] = $email;
  $_SESSION['username'] = $username;
  $_SESSION['success'] = "You are now logged in";
  header('location: index.php');

索引.php

<?php
// Echo session variables that were set on previous page
echo "Your email is: " . $_SESSION['email'] . "<br>";
echo "Your username is: " . $_SESSION['username'] . "";
?>
vltsax25

vltsax251#

这是完整的代码,$username出现(测试不同的用户)

if (isset($_POST['login_user'])) {
  $username = mysqli_real_escape_string($db, $_POST['username']);
  $password = mysqli_real_escape_string($db, $_POST['password']);

  if (empty($username)) {
    array_push($errors, "Username is required");
  }
  if (empty($password)) {
    array_push($errors, "Password is required");
  }

  if (count($errors) == 0) {
    $password = md5($password);
    $query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
    $results = mysqli_query($db, $query);
    if (mysqli_num_rows($results) == 1) {

      $_SESSION['email'] = $email;
      $_SESSION['username'] = $username;
      $_SESSION['success'] = "You are now logged in";
      header('location: index.php');
    }else {
        array_push($errors, "Wrong username or password combination");
    }
  }
}
3xiyfsfu

3xiyfsfu2#

您没有从结果中获得电子邮件,因此$email变量为空。如果电子邮件在用户表中,则需要从结果中分配它。

qc6wkl3g

qc6wkl3g3#

查询数据后不获取结果。使用mysqli\u fetch\u assoc
请注意,我已将mysqli\u real\u escape\u字符串应用于 WHERE 条件参数,用于sql注入相关问题。尽管这不是一个万无一失的解决方案!
更改为:

$query = "SELECT * 
          FROM users 
          WHERE username = '" . mysqli_real_escape_string($db, $username) . 
          " AND password = '" . mysqli_real_escape_string($db, $password) . "'";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 1) {

  $row = mysqli_fetch_assoc($db, $results);
  $_SESSION['email'] = $row['email'];
  $_SESSION['username'] =  $row['username'];
  $_SESSION['success'] = "You are now logged in";

请阅读如何使用准备好的语句来防止与sql注入相关的问题。

相关问题