不要使用 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 (在单独的 css 文件中将 font-weight: bold; 应用于 .name 会更聪明。
如果有任何不清楚的地方,请随时提出问题。