修正:感谢大家的帮助,对于那些需要从某个地方开始的人,你可以将它作为参考
我正在尝试学习PHP SQL HTML,我正在努力正确运行我的代码,你能帮我解决吗?我已经看了很多例子,但是我不能让它工作,我的html表格没有显示出来。这是一个程序,它将搜索用户在搜索表单中输入的内容,并在sql数据库中查找。
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Search Contacts</title>
</head>
<body>
<h3>Search Contacts Details</h3>
<p>You may search either by first or last name</p>
<form method="post" action="#" id="searchform">
<input type="text" name="name">
<input type="submit" name="submit" value="Search">
</form>
<?php
$servername = "xxx";
$username = "xxx";
$password = "xxx";
$dbname = "Staff";
$myquery = $_POST["name"];
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
} // SQL查询
if (!empty($_POST["name"])) {
$sql = "select ID, FirstName, LastName, Email, PhoneNumber from Userlist where FirstName LIKE '%". $myquery ."%'" ;
//Get query on the database
$result = mysqli_query($conn, $sql);
//Check results
if (mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
echo "id:" . $row["ID"] .
" - Name: " . $row["LastName"]. " " . $row["FirstName"]. // Correct here
" - Email: " . $row["Email"] .
" - PhoneNumber: " . $row["PhoneNumber"]. "<br>";
}
} else {
echo "0 results";
}
}
mysqli_close($conn);
?>
</body>
</html>
答案 0 :(得分:3)
您需要使用'
到LIKE
更正SQL语句。
$sql = "select ID, FirstName, LastName, Email, PhoneNumber
from Userlist where FirstName LIKE '%". $myquery ."%'" ;
另外,当您在$myquery
上$_POST
变量时,我认为您应该执行以下操作:
if (!empty($_POST["name"])) {
$myquery = $_POST["name"];
$sql = "select ID, FirstName, LastName, Email, PhoneNumber
from Userlist where FirstName LIKE '%". $myquery ."%'" ;
//Get query on the database
$result = mysqli_query($conn, $sql);
//Check results
if (mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
echo "id:" . $row["ID"] .
" - Name: " . $row["LastName"]. " " . $row["FirstName"]. // Correct here
" - Email: " . $row["Email"] .
" - PhoneNumber: " . $row["PhoneNumber"]. "<br>";
}
} else {
echo "0 results";
}
}
并确保 您的表单操作与您的PHP代码所属的当前页面相同。
答案 1 :(得分:0)
在if(!$ conn){}
之后缺少结束大括号答案 2 :(得分:0)
尝试使用每行输出的回声。 其次要注意“建议”。 第三,为了安全起见,转义你的post变量。