簡體   English   中英

從查詢中獲取任何結果

[英]Getting no result from query

我想顯示登錄我的網站的人的名字。 這是我的login.php文件的代碼,該文件包含在我的網站的一頁中。

<?php

$connect = mysql_connect("localhost","root","") or die("Error");
mysql_select_db("jpnv_db") or die("Couldn't find db");

function login() {
    $username = $_POST['username'];
    $password = $_POST['password'];

    $query = mysql_query("SELECT * FROM customers WHERE `username`='$username' AND `password`='$password'");
    $names = mysql_query("SELECT contactFirstName FROM customers WHERE `username`='$username'");

    if (empty($username)) {
        $errors[] = 'Please fill in your username. <a href="index.php">Click here to try again.</a>';
    }

    if (empty($password)) {
        $errors[] = 'Please fill in your password. <a href="index.php">Click here to try again.</a>';
    }    

    if ($errors==true) {
        foreach ($errors as $error) {
            echo $error.'<br />';
        }
    } else {
        if (mysql_num_rows($query)==true) {
            echo $names['customers'];
        } else {
            echo 'Your username and/or password are incorrect. <a href="index.php">Click here to try again.</a>';
        }
    }
}
?>

密碼不正確的情況是這樣的:

在此處輸入圖片說明

這是我實際成功登錄時的結果:

在此處輸入圖片說明

正如您在我的代碼中看到的那樣,它實際上應該在頂部欄中顯示登錄人員的姓名。 但是,它完全是空的。 我在這里做錯了什么?

您永遠不會從查詢中獲取結果,而需要從查詢中請求正確的列名:

if (mysql_num_rows($query)==true) {
    $name = mysql_fetch_assoc($names)
    echo $name['contactFirstName']; // change the column name here
} else {...

您需要防止SQL注入,否則有人會使您的所有數據消失。

停止使用mysql_*函數 它們不再維護,已正式棄用 而是了解准備好的語句 ,並使用PDO

function login() {

    $username = $_POST['username'];
    $password = $_POST['password'];

    if (empty($username) || empty($password))
    {
      echo "You haven't filled username/password";
      // redirect code here//
    }
    else
    {

    $query = mysqli_query("$con, SELECT * FROM customers WHERE `username`='$username' AND `password`='$password'");
         if ($query && mysqli_num_rows($query)!=0) {
         $row =mysqli_fetch_assoc($query);
         echo "Customer name is : " . $row['customers']; // you need to specify columns in between  ' ' to get it. Change it based on your need.
     }
   }
 }

注意:您應該遷移到MysqliPDO 代碼中的$con是保存數據庫連接的變量。

檢查這一行代碼。 您沒有標識$ name變量。

else {
  //$names variable 
    if $(mysql_num_rows($query)==true) {
      $names = mysql_fetch_all($query);
        echo $names['customers'];
    } else {
        echo 'Your username and/or password are incorrect. <a href="index.php">Click here to try again.</a>';
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM