我正在尝试将我的网站链接到我的数据库以获取结果,但它显示了以下错误:
Warning: mysql_select_db() expects parameter 1 to be string, resource given in C:\wamp\www\SearchEngine\connect.php on line 9
和
Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in C:\wamp\www\SearchEngine\search.php on line 44
这些是这两个文件的代码:
connect.php:
<?php
$con = mysql_connect("localhost", "root", "");
if (!$con)
{
echo "Cannot connect to database";
die();
}
mysql_select_db($con,"SearchEngine");
?>
的search.php:
<?php
//php code goes here
include 'connect.php'; // for database connection
$query = $_GET['q'] // query
?>
<html>
<head>
<title>
Brandon's Search Engine
</title>
<style type="text/css">
#search-result {
font-size: 22;
margin: 5px;
padding: 2px;
}
#search-result:hover {
border-color: red;
}
</style>
</head>
<body>
<form method="GET" action="search.php">
<table>
<tr>
<td>
<h2>
Brandon's Search Engine
</h2>
</td>
</tr>
<tr>
<td>
<input type="text" value="<?php echo $_GET['q']; ?>" name="q" size="80" name="q"/>
<input type="submit" value="Search" />
</td>
</tr>
<tr>
<td>
<?php
//SQL query
$stmt = "SELECT * FROM web WHERE title LIKE '%$query%' OR link LIKE '%$query%'";
$result = mysql_query($stmt);
$number_of_result = mysql_num_rows($result);
if($number_of_result < 1)
echo "Your search did not match any documents. Please try different keywords.";
else
{
//results found here and display them
while($row = mysql_fetch_assoc($result))
{
$title = $row["title"];
$link = $row["link"];
echo "<div id='search-result'>";
echo "<div id='title'" . $title . "</div>";
echo "<br />";
echo "<div id='link'" . $link . "</div>";
echo "</div>";
}
}
?>
</td>
</tr>
</table>
</form>
</body>
</html>
如果可能,请向我解释。
答案 0 :(得分:2)
你的参数错误,应该是
mysql_select_db("SearchEngine",$con);
您的脚本也不安全,您应该执行以下操作:
$con = mysqli_connect("localhost", "root", "");
mysqli_select_db($con,"SearchEngine");
等
替换
$stmt = "SELECT * FROM web WHERE title LIKE '%$query%' OR link LIKE '%$query%'";
带
$stmt = "SELECT * FROM web WHERE title LIKE '%" . mysqli_real_escape_string($con, $query) . "%' OR link LIKE '%" . mysqli_real_escape_string($con, $query) . "%'";
替换
<input type="text" value="<?php echo $_GET['q']; ?>" name="q" size="80" name="q"/>
与
<input type="text" value="<?php echo htmlspecialchars($_GET['q']); ?>" name="q" size="80" name="q"/>
答案 1 :(得分:2)
mysql数据库选择的语法
bool mysql_select_db ( string $database_name [, resource $link_identifier = NULL ] )
尝试使用,
mysql_select_db("SearchEngine",$con);
而不是
mysql_select_db($con,"SearchEngine");
参考:http://us2.php.net/mysql_select_db
注意:尝试使用mysqli_ *函数或PDO而不是mysql_ *函数(不建议使用)
答案 2 :(得分:1)
该错误告诉您第一个参数应该是一个字符串。如果您check the docs,您将首先看到数据库名称,然后是连接资源。
这样做:
mysql_select_db("SearchEngine",$con);
答案 3 :(得分:1)
我可以看到你的错误,它应该是这样的
mysql_select_db("SearchEngine",$con);
答案 4 :(得分:0)
第一个参数必须是数据库名称
mysql_select_db("SearchEngine",$con);
¨