【问题标题】:PHP variable not displaying on pagePHP变量未显示在页面上
【发布时间】:2016-12-13 19:22:08
【问题描述】:

我正在尝试显示我从 mySQLi 服务器获得的 php 变量。但是,它只显示一个空字符串作为“名称”变量。

我的代码是:

$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

【问题讨论】:

    标签: php mysql sql database mysqli


    【解决方案1】:

    您呼叫$result-&gt;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 注入的内容。

    【讨论】:

    • 使用全局会引发内部服务器错误。此外,您在 $row= $result->fetch_assoc(); 上缺少分号如果我没记错的话。
    猜你喜欢
    • 2013-03-24
    • 2021-06-07
    • 1970-01-01
    • 2016-01-09
    • 2015-12-28
    • 2014-10-24
    • 2020-06-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多