查询输出php代码


Query outputs php code

我正在阅读一本关于PhP和MySQL的书,但以下代码无法正常工作:

<html>
    <head>
    <title>Book-O-Rama Search Results</title>
    </head>
<body>
<h1>Book-O-Rama Search Results</h1>
<?php
//short variables
$searchtype = $_POST['searchtype'];
$searchterm = trim($_POST['searchterm']);
echo $searchterm;
if(!$searchtype || !$searchterm) {
    echo 'You have not entered search details.';
    exit;
}
if(!get_magic_quotes_gpc()) {
    $searchtype = addslashes($searchtype);
    $searchterm = addslashes($searchterm);
}
@ $db = new mysqli('localhost', 'root', '', 'books');
if(mysqli_connect_errno()) {
    echo 'Error: could not connect to the database. Please try again later.';
    exit;
} else {
    echo "All right";
}
$query = "select * from books where ".$searchtype." like '%".$searchterm."%";
$result = $db->query($query);
$num_results = $result->num_rows;
echo "<p>Number of books found: ".$num_results."</p>";
for($i=0; $i < $num_results; $i++) {
    $row = $result->fetch_assoc();
    echo "<p><strong>".($i+1).". Title: ";
    echo htmlspecialchars(stripslashes($row['title']));
    echo"</strong><br />Author: ";
    echo stripslashes($row['author']);
    echo "<br /> ISBN: ";
    echo stripslashes($row['isbn']);
    echo "<br />Price: ";
    echo stripslashes($row['price']);
    echo "</p>";
}
$result->free();
$db->close();

?>
</body></html>

它输出这个:

Book-O-Rama Search Results
query($query); $num_results = $result->num_rows; echo "
Number of books found: ".$num_results."
"; for($i=0; $i < $num_results; $i++) { $row = $result->fetch_assoc(); echo "
".($i+1).". Title: "; echo htmlspecialchars(stripslashes($row['title'])); echo"
Author: "; echo stripslashes($row['author']); echo "
ISBN: "; echo stripslashes($row['isbn']); echo "
Price: "; echo stripslashes($row['price']); echo "
"; } $result->free(); $db->close(); ?>

我不明白为什么,而且一开始的echo $searchterm;根本没有执行。附言:我正在使用Xampp localhost运行脚本。

您的问题在于SQL查询。我可以补充一句,这几乎让我泪流满面。

" like '%".$searchterm."%"

您有一个单引号在前%处开始,而在后%处结束。这将把代码的其余部分变成一个字符串。

除此之外,我真的建议你阅读这篇关于净化输入的文章。您的代码非常容易受到攻击,尤其是将经过净化的变量直接放入查询中。对于SQL查询中使用的任何变量,都应该使用PDO绑定变量。对于输出,应该通过htmlspecialchar()(可能还有strip_tag)运行它们。

我建议你选择一本关于PHP/MYSQL的最新书籍。你的代码让我想起了我在2003年买的一个Sams自学PHP的24小时版——没有考虑安全性,只考虑功能。