我做了一个搜索框,你可以输入你想要获取的产品id。当我在产品id框中输入数据时,没有返回结果,有人知道我做错了什么吗?我认为'虽然($row = mysql_fetch_array($result)){'是错误的,但不太确定,因为我所尝试的一切都不起作用。
<div class="searchbox">
<form action="Search.php" method="get">
<fieldset>
<input name="search" id="search" placeholder="Search for a Product" type="text" />
<input id="submit" type="button" />
</fieldset>
</form>
</div>
<div id="content">
<ul>
<?php
// connect to the database
include('base.php');
$search = mysql_real_escape_string($_GET['search']);
$query = "SELECT * FROM Product WHERE ProductID LIKE '%{$search}%'";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
echo "<li><span class='name'><b>{$row['ProductID']}</b></span></li>";
}
不要使用mysql特有的语法,它已经过时了,以后会给你带来真正的麻烦,特别是当你决定使用sqlite或postgresql时。
使用PDO连接,您可以像这样初始化一个:
// Usage: $db = connectToDatabase($dbHost, $dbName, $dbUsername, $dbPassword);
// Pre: $dbHost is the database hostname,
// $dbName is the name of the database itself,
// $dbUsername is the username to access the database,
// $dbPassword is the password for the user of the database.
// Post: $db is an PDO connection to the database, based on the input parameters.
function connectToDatabase($dbHost, $dbName, $dbUsername, $dbPassword)
{
try
{
return new PDO("mysql:host=$dbHost;dbname=$dbName;charset=UTF-8", $dbUsername, $dbPassword);
}
catch(PDOException $PDOexception)
{
exit("<p>An error ocurred: Can't connect to database. </p><p>More preciesly: ". $PDOexception->getMessage(). "</p>");
}
}
然后初始化变量:
$host = 'localhost';
$user = 'root';
$dataBaseName = 'databaseName';
$pass = '';
现在可以通过
访问数据库了$db = connectToDatabase($host , $databaseName, $user, $pass); // You can make it be a global variable if you want to access it from somewhere else.
然后你应该确保你有变量:
$search = isset($_GET['search']) ? $_GET['search'] : false;
如果某些东西失败了,你可以跳过数据库。
if(!$search)
{
//.. return some warning error.
}
else
{
// Do what follows.
}
现在您应该构造一个可以用作准备查询的查询,也就是说,它接受准备好的语句,以便您准备查询,然后执行将被放入查询中执行的变量数组,同时避免sql注入:
$query = "SELECT * FROM Product WHERE ProductID LIKE :search;"; // Construct the query, making it accept a prepared variable search.
$statement = $db->prepare($query); // Prepare the query.
$statement->execute(array(':search' => $search)); // Here you insert the variable, by executing it 'into' the prepared query.
$statement->setFetchMode(PDO::FETCH_ASSOC); // Set the fetch mode.
while ($row = $statement->fetch())
{
$productId = $row['ProductID'];
echo "<li class='name><strong>$productId</strong></li>";
}
哦,是的,不要用b标签,它过时了。使用strong代替(使用font-weight: bold;在一个单独的CSS文件中。name。
如有不清楚之处,请随时提问。
删除$search前后的{}。
应:$query = "SELECT * FROM Product WHERE ProductID LIKE '%$search%'";
您可以使用:
$result = mysql_query($query) or die($query."<br/><br/>".mysql_error());
确认数据正在返回。