<?php
if (!isset($_POST['submit']))
$TheName = $_POST['TheName'];
$host = "localhost";
$user = "root";
$pass = "";
$db = "onlinebookclub";
$link = mysqli_connect($host, $user, $pass, $db);
$query = "SELECT * FROM author WHERE name = $TheName";
//3.excute SQL query
$result = mysqli_query($link, $query) or die('Error querying database');
//5. Close Connection
mysqli_close($link);
//4. process the result
?>
<html>
<head>
<hr>
<title></title>
</head>
<body>
<?php if (!empty($row)) {
while ($row = mysqli_fetch_array($result)) {
$author_id = $row['author_id'];
$name = $row['name'];
$gender = $row['gender'];
$birth_year = $row['birth_year'];
$introduction = $row['introduction'];
?>
<table>
<tr>
<td>Name: </td>
<td> <?php echo $name; ?><br/></td>
</tr>
<tr>
<td>Author ID: </td>
<td><?php echo $author_id; ?><br></td>
</tr>
<tr>
<td>Gender: </td>
<td><?php echo $gender; ?><br/></td>
</tr>
<tr>
<td>Birth Year: </td>
<td><?php echo $birth_year; ?><br></td>
</tr>
<tr><td><hr/></td>
<td><hr/></td>
</tr>
</table>
<?php
}
}else {
echo "No records found";
}
?>
</body>
</html>
我的PHP文件没有检索到正确的数据。它应该从我的数据库中检索相关的详细信息,但它显示的是没有找到记录。我怎样才能解决这个问题?我尝试将关闭链接移动到结尾,但错误仍然存在。
答案 0 :(得分:4)
您正在使用此行:
$query = "SELECT * FROM author WHERE name = $TheName";
你没有使用过引号或转义:
$query = "SELECT * FROM author WHERE name = '{$TheName}'";
正如其他人所说,注意注射,即使使用$TheName = mysqli_real_escape_string($link, $TheName)
;总比没有好(在查询之前)。
答案 1 :(得分:3)
问题在于您的查询。您缺少'正在寻找的名称变量'。它应该是:
$query = "SELECT * FROM author WHERE name = '$TheName'";
由于@jeroen已经声明最好使用预准备语句来避免SQL注入,并且绑定到查询时变量也会被正确转义。
答案 2 :(得分:3)
我认为你的问题就在这里。
if (!isset($_POST['submit']))
$TheName = $_POST['TheName'];
将其更改为:
if (isset($_POST['submit']))
{
$TheName = $_POST['TheName'];
$TheName = $_POST['TheName']
,这是错误的<强>更新强>
注意其他人已经说过的话:
答案 3 :(得分:2)
$TheName = mysqli_real_escape_string($link, $TheName);
并且,将$TheName
放在单引号中。
$query = "SELECT * FROM author WHERE name = '$TheName'";