2016-10-10 3 views
0

У меня есть сценарий. Он отлично работает с точным соответствием &, но когда я ищу несколько ключевых слов, он возвращает null и черную страницу по моему запросу.Как искать ключевые слова в PHP?

Вот мой код:

<!doctype html public "-//w3c//dtd html 3.2//en"> 

<html> 
<head> 

</head> 

<body> 
<?Php 
ini_set('display_errors', true);//Set this display to display all erros while testing and developing the script 
error_reporting(0);// With this no error reporting will be there 
include "include/z_db.php"; 


$todo=$_POST['todo']; 
$search_text=$_POST['search_text']; 

if(strlen($serch_text) > 0){ 
if(!ctype_alnum($search_text)){ 
echo "Data Error"; 
exit; 
} 
} 
////////// Displaying the search box ///// 
echo "<table> 
<tr><td colspan=2 align='center'>"; 

echo "<form method=post action=''><input type=hidden name=todo value=search> 
<input type=text name=search_text value='$search_text'><input type=submit value=Search><br> 
<input type=radio name=type value=any checked>Match any where 
<input type=radio name=type value=exact>Exact Match 

</form> 
"; 

echo "</td></tr>"; 

/////////// if form is submitted the data processing is done here/////////////// 
echo "<tr><td width='600' valign=top>"; 

if(isset($todo) and $todo=="search"){ 

$type=$_POST['type']; 

$search_text=ltrim($search_text); 
$search_text=rtrim($search_text); 

    if($type<>"any"){ 
$query="select * from student where name='$search_text'"; 
     }else{ 
$kt=split(" ",$search_text);//Breaking the string to array of words 
// Now let us generate the sql 
      while(list($key,$val)=each($kt)){ 
if($val<>" " and strlen($val) > 0){$q .= " name like '%$val%' or ";} 

      }// end of while 
$q=substr($q,0,(strLen($q)-3)); 
// this will remove the last or from the string. 
$query="select * from student where $q "; 
     } // end of if else based on type value 
echo "<span style='background-color= #FFFF00'>$query</span><br>"; 
$count=$dbo->prepare($query); 
$count->execute(); 
$no=$count->rowCount(); 
if($no > 0){echo " No of records = ".$no."<br><br>"; 
echo "<table><tr><th>ID</th><th>Name</th><th>Class</th><th>Mark</th><th>Sex</th></tr>"; 
foreach ($dbo->query($query) as $row){ 
echo "<tr><td>$row[id]</td><td>$row[name]</td><td>$row[class]</td> 
<td>$row[mark]</td><td>$row[sex]</td></tr>"; 
} 
echo "</table>"; 
}else { 
echo " No records found "; 
} 

}// End if form submitted 
echo "</td><td width='400' valign=top>"; 
echo " Full records here "; 
$query="select * from student"; 


echo "<table><tr><th>ID</th><th>Name</th><th>Class</th><th>Mark</th><th>Sex</th></tr>"; 
foreach ($dbo->query($query) as $row){ 
echo "<tr><td>$row[id]</td><td>$row[name]</td><td>$row[class]</td> 
<td>$row[mark]</td><td>$row[sex]</td></tr>"; 
} 
echo "</table>"; 

echo "</td></tr></table>"; 
?> 
</body> 

</html> 
<!doctype html public "-//w3c//dtd html 3.2//en"> 

<html> 
<head> 
<title>Demo of Search Keyword using PHP and MySQL</title> 
</head> 

<body> 
<?Php 
ini_set('display_errors', true);//Set this display to display all erros while testing and developing the script 
error_reporting(0);// With this no error reporting will be there 
include "include/z_db.php"; 


$todo=$_POST['todo']; 
$search_text=$_POST['search_text']; 

if(strlen($serch_text) > 0){ 
if(!ctype_alnum($search_text)){ 
echo "Data Error"; 
exit; 
} 
} 
////////// Displaying the search box ///// 
echo "<table> 
<tr><td colspan=2 align='center'>"; 

echo "<form method=post action=''><input type=hidden name=todo value=search> 
<input type=text name=search_text value='$search_text'><input type=submit value=Search><br> 
<input type=radio name=type value=any checked>Match any where 
<input type=radio name=type value=exact>Exact Match 

</form> 
"; 

echo "</td></tr>"; 

/////////// if form is submitted the data processing is done here/////////////// 
echo "<tr><td width='600' valign=top>"; 

if(isset($todo) and $todo=="search"){ 

$type=$_POST['type']; 

$search_text=ltrim($search_text); 
$search_text=rtrim($search_text); 

    if($type<>"any"){ 
$query="select * from student where name='$search_text'"; 
     }else{ 
$kt=split(" ",$search_text);//Breaking the string to array of words 
// Now let us generate the sql 
      while(list($key,$val)=each($kt)){ 
if($val<>" " and strlen($val) > 0){$q .= " name like '%$val%' or ";} 

      }// end of while 
$q=substr($q,0,(strLen($q)-3)); 
// this will remove the last or from the string. 
$query="select * from student where $q "; 
     } // end of if else based on type value 
echo "<span style='background-color= #FFFF00'>$query</span><br>"; 
$count=$dbo->prepare($query); 
$count->execute(); 
$no=$count->rowCount(); 
if($no > 0){echo " No of records = ".$no."<br><br>"; 
echo "<table><tr><th>ID</th><th>Name</th><th>Class</th><th>Mark</th><th>Sex</th></tr>"; 
foreach ($dbo->query($query) as $row){ 
echo "<tr><td>$row[id]</td><td>$row[name]</td><td>$row[class]</td> 
<td>$row[mark]</td><td>$row[sex]</td></tr>"; 
} 
echo "</table>"; 
}else { 
echo " No records found "; 
} 

}// End if form submitted 
echo "</td><td width='400' valign=top>"; 
echo " Full records here "; 
$query="select * from student"; 


echo "<table><tr><th>ID</th><th>Name</th><th>Class</th><th>Mark</th><th>Sex</th></tr>"; 
foreach ($dbo->query($query) as $row){ 
echo "<tr><td>$row[id]</td><td>$row[name]</td><td>$row[class]</td> 
<td>$row[mark]</td><td>$row[sex]</td></tr>"; 
} 
echo "</table>"; 

echo "</td></tr></table>"; 
?> 
</body> 

</html> 

Подключение к MySQL:

<?php 
global $dbo; 

$info['dbhost_name'] = "localhost"; 
$info['database'] = "search"; // database name 
$info['username'] = "root"; // userid 
$info['password'] = ""; // password 

$dbConnString = "mysql:host=" . $info['dbhost_name'] . "; dbname=" . $info['database']; 

$dbo = new PDO($dbConnString, $info['username'], $info['password']); 
$dbo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT); 
//$dbo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 

$error = $dbo->errorInfo(); 
if($error[0] != "") { 
    echo "string"; 
} 

?> 

Результат после запроса представлен:

Result after query submitted

+0

Вы должны поместить свое входное значение в массив и выполнить поиск в этом массиве – mhmd

+0

. вашему тегу стиля нужно немного исправить 'background-color = # FFFF00'' background-color: # FFFF00' –

+0

, можете ли вы записать здесь, как я могу поместить значение запроса в массив Vural Ascar https://stackoverflow.com/users/1524622/vural-acar – Ali

ответ

0
$q = array(); // create an array 
    $sq = ""; // this variable will be used in the query 
if(isset($_POST['txt_projectname']) && !empty($_POST['txt_projectname'])){ 
    $projectname = mysqli_real_escape_string($conn,$_POST['txt_projectname']); 
    $q[] = "db_projectname='".$projectname."' ";  
    } // take the variable from input after submit and put it in the array 
    if(isset($_POST['txt_location']) && !empty($_POST['txt_location'])){ 
    $location = mysqli_real_escape_string($conn,$_POST['txt_location']); 
    $q[] = "db_location='".$location."' ";  
    } 
    $first = true; 

    foreach($q as $qu){ 
     if($first){ 
     $sq .= " where ".$qu;  
     $first = false; 
     }else{ 
     $sq .= " and ".$qu;   
     } // for loop to use where and and in the query 
    } 
$sql=mysqli_query($conn,"select * from table {$sq} ")or die(mysqli_error($conn)); 

Вы можете сделать что-нибудь g like this

+0

Можете ли вы объяснить это в соответствии с моим кодом? – Ali

+0

вам не нужен ваш код, вы можете удалить свой поисковый код и использовать то, что я положил для вас. – mhmd

+0

. Я думаю, было бы лучше объяснить ваш ответ, вместо того чтобы внедрить blob кода и сказать: «Вы можете сделать что-то подобное», –