无法使用php从mysql获取变量

x7yiwoj4  于 2021-06-19  发布在  Mysql
关注(0)|答案(2)|浏览(316)

我需要从mysql数据库获取一些数据(它确实存在)来继续分析它。所以,我的代码里有:

if (count($errors) == 0)  
$password = md5($password); 
$query = "SELECT username, password, email FROM trackowners WHERE username='$username' AND password='$password'"; 
$results = mysqli_query($db, $query); 
if (mysqli_num_rows($results) == 1) {
  ///////////
  $_SESSION['username'] = $username;
  $_SESSION['success'] = "You are now logged in";
  $_SESSION['email'] = $email;
  header('location: index.php');
}else {
  array_push($errors, "Wrong username/password combination");
} }

然后我尝试使用变量$\u session['username']和email one:

<?php  if (isset($_SESSION['username'])) : ?>
    <p>Welcome <strong><?php echo $_SESSION['username']; ?></strong> // Here are your profile settings.</p>

    <p> <a href="index.php?logout='1'" style="color: red;">logout</a> </p>
<?php endif ?>

  <?php  if (isset($_SESSION['username'])) : ?>
  <p>Your e-mail<strong><?php echo $_SESSION['email']; ?></strong> //</p>
<?php endif ?>

这里我得到用户名变量,但我不能从电子邮件变量得到任何东西。有什么问题吗?
提前谢谢!

h5qlskok

h5qlskok1#

我对您的代码有很多疑问(不要使用md5进行密码散列,而是使用php内置散列方法)。但是继续担任@nicolas的职务
根据杰伊·布兰查德的建议编辑

// Make sure your session is started
session_start();    

if (count($errors) == 0){
    // Make sure to store your passwords with the same function
    $password = password_hash($password, PASSWORD_DEFAULT ); 
    // Prepare your query with placeholders
    $query = $pdo->prepare('SELECT username, password, email FROM trackowners WHERE username=? AND password=?');
    // Execute your query
    if($query->execute(array($username, $password)))
    {
        // Loop through result set
        while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
            $_SESSION['username'] = $row['username'];
            $_SESSION['email'] = $row['email'];
            $_SESSION['success'] = "You are now logged in";     
        }
        header('location: index.php');  
    }
    else
    {
        array_push($errors, "Wrong username/password combination"); 
    }
}

正如@nicolas所提到的,他读了一些准备好的语句来防止sql注入。

lrl1mhuk

lrl1mhuk2#

实际上,您从未从查询结果中访问数据。你需要使用 $result 变量来设置会话变量。

if (count($errors) == 0){
$password = md5($password); 
$query = "SELECT username, password, email FROM trackowners WHERE username='$username' AND password='$password'"; 
$results = mysqli_query($db, $query); 
if (mysqli_num_rows($results) == 1) {
  // Here i'm accessing the results data from your query
  $data = mysqli_fetch_assoc($result)[0];
  //The data is an associative array. 
  $_SESSION['username'] = $data['username'];
  $_SESSION['success'] = "You are now logged in";
  $_SESSION['email'] = $data['email'];
  header('location: index.php');
}else {
  array_push($errors, "Wrong username/password combination");
} 
}

我还想提到的是,您的代码容易受到sql注入的攻击。你应该尝试绑定你的参数。

相关问题