2016-12-13 110 views
1

我想顯示一個變量從php我從一個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 

回答

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注入。

+0

使用全局引發內部服務器錯誤。另外,您在 $ row = $ result-> fetch_assoc();中缺少分號。 如果我沒有弄錯。 –