使用PHP无法从MySQL获取变量

时间:2018-11-16 17:56:04

标签: php mysql session md5

我需要从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 ?>

在这里,我正在获取用户名变量,但无法从电子邮件变量中获取任何信息。有什么问题吗?

谢谢!

2 个答案:

答案 0 :(得分:0)

我对您的代码有很多疑问(请勿将MD5用于密码哈希,而应使用PHP build in hashing method)。但是继续在@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注入。

答案 1 :(得分:-1)

您从不实际访问查询结果中的数据。您需要像这样使用$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注入的攻击。您应该尝试绑定参数。