我正在尝试搜索数据库并查看它是否与用户条目匹配。然而,到目前为止我的代码我只是在输入数据库中的学生姓名和号码时不断得到“学生不存在”,当我输入一个不存在的名称和号码时,它什么都没显示。我是PHP和mysql的新手,如果有人可以帮助我解释为什么我的代码不起作用,我将非常感激。我的表单在另一页上。这是我要求用户输入他们的名字只是为了表明我正在拉正确的$ _POST。我只是测试回显出的名称和数字,以确保代码正常工作......现在就是这样。
<form action="next.php" method="post">
Name: <input type="text" name="name" placeholder="Name" required="required" maxlength="50">
<br><br>
Student Number: <input type="text" name= "snumber" required="required" maxlength="9">
<br><br>
next.php
<?php
require 'connect.php';
//linking up to the database
$link = mysqli_connect(HOST, USER, PASS, DB) or die (mysqli_connect_error());
//making a variable from the user data
$name = mysqli_real_escape_string ($link, $_POST["name"]);
$number = mysqli_real_escape_string ($link, $_POST["snumber"]);
$course = $_POST["pcourse"];
// select all from table student which show student name and number
$squery = "SELECT * FROM students WHERE uid='$number' AND student = '$name'";
$sresult = mysqli_query($link, $squery);
// check is name and number entered by user equals what is in database
$sfound =0;
while ($srow = mysqli_fetch_array($sresult)) {
if ($name == $srow['uid'] && $number == $srow['student']) {
echo "$srow[uid] $srow[student]";
} else{
echo "Student doesn't exist";
$sfound =1;
} // end of if ($name == $srow['uid'] && $number == $srow['student'])
} // end of while ($srow = mysqli_fetch_array($sresult))
mysqli_close ($link);
?>
<html>
<body>
<form action="index.php" method="post">
<br>
<input type = "submit" value="back" name="back">
</form>
</body>
</html>
答案 0 :(得分:0)
虽然示例缺少结束HTML
标记,但您的</form>
似乎无效。
现在到PHP
。我修正了一些错误。这是代码:
PHP
<?php
require 'connect.php';
//linking up to the database
$link = mysqli_connect(HOST, USER, PASS, DB) or die (mysqli_connect_error());
//making a variable from the user data
$name = mysqli_real_escape_string ($link, $_POST["name"]);
$number = mysqli_real_escape_string ($link, $_POST["snumber"]);
$course = $_POST["pcourse"];
// select all from table student which show student name and number
$squery = "SELECT * FROM students WHERE uid=".$number." AND student = '".$name."'";
$sresult = mysqli_query($link, $squery);
// check if name and number entered by user equals what is in database
$sfound =0;
while ($srow = mysqli_fetch_assoc($sresult))
{
if ($name == $srow['student'] && $number == $srow['uid']) echo $srow['uid'].' '.$srow[student];
else
{
echo "Student doesn't exist";
$sfound =1;
} // end of if ($name == $srow['student'] && $number == $srow['uid'])
} // end of while ($srow = mysqli_fetch_array($sresult))
mysqli_close ($link);
?>
答案 1 :(得分:0)
您需要查看mysqli_real_escape_string
生成的结果,它们可能为空。这可能是您的数据库查询检索0行的原因。如果您的连接$link
也是空的,那么这应该是首要原因。