我想显示登录我网站的人的名字。这是我的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>';
}
}
}
?>
这是密码错误时的结果:
这是我实际登录成功的结果:
正如您在我的代码中所看到的,它实际上应该显示在顶部栏中登录的人的姓名。但是,它完全是空的。我在这里做错了什么?
答案 0 :(得分:5)
您永远不会从查询中获取结果,您需要从查询中请求正确的列名称:
if (mysql_num_rows($query)==true) {
$name = mysql_fetch_assoc($names)
echo $name['contactFirstName']; // change the column name here
} else {...
You need to prevent SQL Injection或某人会使您的所有数据都消失。
请stop using mysql_*
functions。它们不再被维护,而是officially deprecated。请改为了解prepared statements,并使用PDO。
答案 1 :(得分:0)
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.
}
}
}
注意:您应该迁移到 Mysqli 或 PDO 。代码中的$con
是保存数据库连接的变量。
答案 2 :(得分:0)
检查这行代码。您没有识别$ 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>';
}
}