作業中のシステムで検索ツールバーを作成しましたが、検索対象が実行されません。検索したキーワードがデータベースのテーブルで見つかった場合でも、常に結果が返されません。plsは、コードを分析するのに役立ちます。コードを事前に見逃したり、間違ったりしています。ここに私のコードがあります。search.php
<form method="post" action="search.php">
<p><input type="text" name="keywords"><input type="submit" value="Search"></p>
</form>
<?php
include 'connect/func.inc.php';
if(isset($_POST['keywords'])){
$suffix = '';
//trim is for ignoring spaces on the input type text
$keywords = mysql_real_escape_string(htmlentities(trim($_POST['keywords'])));
$errors = array();
if(empty($keywords)){
$errors[]='Please enter a search keyword';
}
else if (strlen($keywords)<0) {
//strlen is for the no. of char
$errors[]='Please three or more characters';
}else if (search_results($keywords) === false){
$errors[]='Your search for '.$keywords.' returned no results';
}
if (empty($errors)) {
//search
$results = search_results($keywords);
$results_num = count($results);
$suffix = ($results_num !=1) ? 's': '';
echo '<p>Your search for<strong>'. $keywords.'</strong> returned <strong>'. $results_num .'</strong>result',$suffix, '</p>';
foreach($results as $result) {
echo '<p><strong>', $result['studId'], '</strong><br>', $result['fname'], $result['mname'], $result['lname'],'</p>';
}
//print_r(search_results($keywords));
} else {
foreach($errors as $error) {
echo $error, '</br>';
}
}
}
?>
function.inc.php
<?php
include 'db.inc.php';
function search_results($keywords) {
$returned_results = array();
$where = "";
$keywords = preg_split('/[\s]+/', $keywords);
//preg_split select evry word and ignore many spaces
$total_keywords = count($keywords);
foreach($keywords as $key=>$keyword){
$where .= "`keywords` LIKE '%$keyword%'";
if($key != ($total_keywords -1)) {
$where .= " AND ";
}
}
//echo $where;
$results = "SELECT `studId`, LEFT(`fname`, 20) as `fname`, LEFT(`lname`, 20) as `lname`, LEFT(`mname`, 20) as `mname` FROM tbl_student WHERE $where";
//echo $results;
$results_num = ($results = mysql_query($results)) ? mysql_num_rows($results) : 0;
if($results_num === 0) {
return false;
} else {
//get info into database
while ($results_row = mysql_fetch_assoc($results)) {
$returned_results[] = array(
'studId'=> $results_row['studId'],
'fname'=> $results_row['fname'],
'mname'=> $results_row['mname'],
'lname'=> $results_row['lname']);
}
return $returned_results;
}
}
?>
私のテーブルはこんな感じです。tbl_student
studId fname mname lname
c-1111 peter jan yu
c-1112 jane trish li