我正在尝试使用ajax和php创建一个搜索框。出于某种原因,我得到了
"Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\wamp\www\livesearch\livesearch.php on line 30"
以下代码:
session_start();
include("_/inc/dbcon.php");
$link = mysql_connect($host, $login, $pw);
mysql_select_db($database);
if($link){
echo 'connect';
}
// Define Output HTML Formating
$html = '';
$html .= '<li class="result">';
$html .= '<a target="_blank" href="urlString">';
$html .= '<h3>nameString</h3>';
$html .= '<h4>functionString</h4>';
$html .= '</a>';
$html .= '</li>';
// Get Search
$search_string = preg_replace("/[^A-Za-z0-9]/", " ", $_POST['query']);
$search_string = mysql_real_escape_string($search_string);
// Check Length More Than One Character
if (strlen($search_string) >= 1 && $search_string !== ' ') {
// Build Query
$query = 'SELECT * FROM sp_user WHERE function LIKE "%'.$search_string.'%" OR name LIKE "%'.$search_string.'%" OR surname LIKE "%'.$search_string.'%" OR username LIKE "%'.$search_string.'%"';
// Do Search
$result = mysql_query($query);
while($results = mysql_fetch_array($result)) {
$result_array[] = $results;
}
// Check If We Have Results
if (isset($result_array)) {
foreach ($result_array as $result) {
// Format Output Strings And Hightlight Matches
$display_function = preg_replace("/".$search_string."/i", "<b class='highlight'>".$search_string."</b>", $result['function']);
$display_name = preg_replace("/".$search_string."/i", "<b class='highlight'>".$search_string."</b>", $result['name']);
$display_url = 'http://php.net/manual-lookup.php?pattern='.urlencode($result['function']).'&lang=en';
// Insert Name
$output = str_replace('nameString', $display_name, $html);
// Insert Function
$output = str_replace('functionString', $display_function, $output);
// Insert URL
$output = str_replace('urlString', $display_url, $output);
// Output
echo($output);
}
}else{
// Format No Results Output
$output = str_replace('urlString', 'javascript:void(0);', $html);
$output = str_replace('nameString', '<b>No Results Found.</b>', $output);
$output = str_replace('functionString', 'Sorry :(', $output);
// Output
echo($output);
}
答案 0 :(得分:1)
您必须使用mysql_fetch_assoc()
(这样您才能在Associate array
中使用字段名称),并且您还必须在字段名称中添加引号,因为您使用了一些关键名称,例如{根据@Frederik Spang的建议{1}},name
等Reserved Words in MySQL
function
在指定字段名称时,在字段名称中使用反引号(“`”)是一种很好的做法。
您还应该使用
检查$query = 'SELECT * FROM sp_user WHERE `function` LIKE "%'.$search_string.'%" OR `name` LIKE "%'.$search_string.'%" OR `surname` LIKE "%'.$search_string.'%" OR `username` LIKE "%'.$search_string.'%"';
是否有记录
$result