首页 > 解决方案 > 无法使用 PHP 从 MySQL 获取变量

问题描述

我需要从 MySQL DB(它肯定存在)中获取一些数据来继续分析它。所以,我的代码中有什么:

  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");
} }

然后我尝试使用变量 $_SESSION['username'] 并通过电子邮件发送:

<?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 ?>

在这里我得到了用户名变量,但我无法从电子邮件变量中得到任何东西。有什么问题?

提前致谢!

标签: phpmysqlsessionmd5

解决方案


我对您的代码有很多疑问(不要使用 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 所提到的,阅读了Prepared statements以防止 sql 注入。


推荐阅读