我正在尝试创建一个搜索我的网站,我在做这件事时遇到了很多麻烦。在我的movies
数据库中,我有两个表:movieinfo
和movie_genres
。在movieinfo
下,有Movie_Name
,actor1
,actor2
,actor3
,actor4
。在movie_genres
表下,有Genre_Id
。 (每个表中有更多列,但我只想搜索这些列。)
我目前的代码是:
<?php
if ($_GET) {
$search = $_GET['search'];
$connect = mysql_connect("localhost","root","spencer");
if($connect) {
mysql_select_db("movies", $connect);
$query = "SELECT Movie_Name, actor1, actor1, actor1, actor1, Genre_Id FROM movieinfo, movie_genres WHERE * LIKE '%:search%' OR actor1 LIKE '%:search%' OR actor2 LIKE '%:search%' OR actor3 LIKE '%:search%' OR actor4 LIKE '%:search%' OR Genre_Id = ? ";
$results = mysql_query($query);
while($row = mysql_fetch_array($results)) {
echo $row['Poster'] . "<br/>" . $row['Movie_Name'];
}
} else {
die(mysql_error());
}
}
?>
我正在搜索的movieinfo
中的所有内容都是VARCHAR
,而movie_genres
是INT
(这会带来很大的不同)。我想我接近代码应该是什么,但我不知道。
截至目前,我在尝试搜索时遇到以下错误:
警告:mysql_fetch_array()要求参数1为资源,在第12行的C:\ xampp \ htdocs \ movies \ get_search.php中给出布尔值
新代码:
<?php
// Connection data (server_address, database, name, poassword)
$hostdb = 'localhost';
$namedb = 'movies';
$userdb = 'root';
$passdb = 'spencer';
try {
// Connect and create the PDO object
$conn = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb);
$conn->exec("SET CHARACTER SET utf8"); // Sets encoding UTF-8
}
catch (PDOException $e) {
$v_errormsg = $e->getMessage();
$error_str = <<<END_HTML
<h2> Error connecting to database: Message: $v_errormsg <h2>
END_HTML;
echo $error_str;
die;
}
$sql = <<<END_SQL
SELECT Movie_Name FROM movieinfo WHERE Movie_Name LIKE '%":search"%' ";
END_SQL;
try {
$sth = $conn->prepare($sql);
$sth->execute();
}
catch (PDOException $e) {
$v_errormsg = $e->getMessage();
$error_str = <<<END_HTML
<h2> Error selecting data: Message: $v_errormsg <h2>
END_HTML;
echo $error_str;
die;
}
$num_rows = 0;
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
$Movie_Name = $row['Movie_Name'];
}
echo $row['Movie_Name'];
?>
答案 0 :(得分:1)
LIKE :search
并绑定'%' . $search . '%'
作为值。答案 1 :(得分:0)
您收到的查询无效,因为您正在使用PDO中的绑定参数语法
从非常简单的事情开始,比如
$search= mysql_escape_string($search);
$query = "SELECT Movie_Name FROM movie_info WHERE name LIKE '%".$search."%';
一旦你开始工作,转到更复杂的逻辑...
更好的是,使用PDO进行查询:
<?php
$stmt = $db->prepare("SELECT * FROM table WHERE id=:id AND name=:name");
$stmt->bindValue(':id', $id, PDO::PARAM_INT);
$stmt->bindValue(':name', $name, PDO::PARAM_STR);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
示例来自:http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers