PHP变量不在页面上显示

时间:2016-12-13 19:22:09

标签: php mysql sql database mysqli

我正在尝试显示来自mySQLi Server的php变量。但是,它只显示一个空字符串作为'name'变量。

我的代码是:

$GLOBALS[name] = "";

$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    die("<br>Connection failed: " . $conn->connect_error);
    $out = "Error when connecting to the database.";
} else {
    echo "<br>Connected successfully";
    $sql = "SELECT name, pwd FROM server1.us WHERE UPPER(eml) = UPPER('$email')";
    $result = $conn->query($sql);
    $pwdHash = "";

    if ($result->num_rows == 0) {
        $out = "Your email is not registered yet.";
    }
    else {
        while($row = $result->fetch_assoc()) {
            $pwdHash = $row['pwd'];
        }
    }

    if (password_verify($pwd, $pwdHash) == false) {
        $out = "Your passwords do not match!";
    }
    else if($email == '') {
        $out = "You have to input an email.";
    }       
    else if($pwd == '') {
        $out = "You have to input a password.";
    }
    else {
        while($row = $result->fetch_assoc()) {
        $name = $row['name'];
    }
}
$conn->close();

我的代码显示值:

<?php
        if($out == null) {
            echo "<h3>Thank you for logging in, $name!</h3>";
            echo "<p>You will be redirected...</p>";
        } else {
            echo "<h3>Oops! Apparently something went wrong...</h3>";
            echo "<p>$out</p>";
            echo "<p>You can try again <a data-toggle='modal' data-target='#loginModal'>here</a> .</p>";
        }
?>

执行时,不会给出错误,但输出为

  

感谢您登录,''!     你将被重定向......

我在数据库中的表格包含以下列:

id
name
eml
pwd

1 个答案:

答案 0 :(得分:0)

您正在调用$result->fetch_assoc()两次(首先要检查密码,然后再想要获取名称)。你不应该这样做。只需调用一次,而不是循环调用:

$result = $conn->query($sql);
$pwdHash = "";

if ($result->num_rows == 0) {
    $out = "Your email is not registered yet.";
}
else {
    $row = $result->fetch_assoc();
    $pwdHash = $row['pwd'];
}

// [...]

$name = $row['name'];

另外,从第一行$GLOBALS[name] = "";开始,我假设此代码在函数中执行,并且您希望$name变量是全局变量,因此可以在您的视图中访问后面。

如果这是你想要的,你应该使用global关键字:

global $name;
$name = $row['name'];

值得注意的是:将用户提供的数据$email注入SQL查询的方式非常危险。阅读一些关于SQL注入的内容。