How to prevent a database search from running on an empty string? - php

With my current code when I enter an empty string or a string of one space in the search input field I get every item in the database as a result. How can i make it so that the search doesn't run when an empty string is entered?
<form action="search.php" method="POST">
<input type="text" name="search" placeholder="search site">
<button type="submit" name="submit-search"><img src="../assets/search icon-05.png"></button>
</form>
<?php
if (isset($_POST['submit-search'])){
$search = mysqli_real_escape_string($conn, $_POST['search']);
$sql = "SELECT * FROM articles WHERE title LIKE '%$search%' OR abstract LIKE '%$search%' OR keywords LIKE '%$search%'";
$result = mysqli_query($conn, $sql);
$queryResult = mysqli_num_rows($result);
if ($queryResult > 0){
echo $queryResult . " results found";
while ($row = mysqli_fetch_assoc($result)){
echo "<div class='articleItem'>
<h2>".$row['title']."</h2>
<p>".$row['abstract']."</p>
<a href=".$row['link']." target='_blank'>".$row['link']."</a>
</div>";
}
}
else {
echo "There are no results matching your search.";
}
}
?>

Check if isset, then trim, then confirm it still has at least one character.
if ( isset( $_POST['submit-search'] ) ) {
$search = trim( (string) $_POST['submit-search'] );
if ( isset( $search[0] ) ) { // Has at least one character?
// Run query.
}
}
If you have PHP 7+, here's a more terse syntax.
$search = trim( (string) ( $_POST['submit-search'] ?? '' ) );
if ( isset( $search[0] ) ) { // Has at least one character?
// Run query.
}

You can check string length with strlen. A trim can be additionally used to remove white spece search also.
$hasResult = false ; //default mark no result.
if (isset($_POST['submit-search']) && strlen(trim($_POST['submit-search'])) > 0) {
$search = mysqli_real_escape_string($conn, $_POST['search']);
$sql = "SELECT * FROM articles WHERE title LIKE '%$search%' OR abstract LIKE '%$search%' OR keywords LIKE '%$search%'";
$result = mysqli_query($conn, $sql);
$queryResult = mysqli_num_rows($result);
if ($queryResult > 0) {
$hasResult = true ; //mark result found
echo $queryResult . " results found";
while ($row = mysqli_fetch_assoc($result)) {
echo "<div class='articleItem'>
<h2>" . $row['title'] . "</h2>
<p>" . $row['abstract'] . "</p>
<a href=" . $row['link'] . " target='_blank'>" . $row['link'] . "</a>
</div>";
}
}
}
if( ! $hasResult ) { //Move to a common section
echo "There are no results matching your search.";
}

Use the below function to get the query string
<?php
$arr_with_index['title'] = $_POST['search'];
$search_qry = getLikeSearchQuery($arr_with_index)
// Add this $search_qry in your query string. This help you to searc N number of values
// For Array and Equal values
function getSearchQuery($arr_with_index) {
$search_qry = "";
if(isset($arr_with_index)){
foreach(#$arr_with_index as $index => $value) {
if(is_array($value)) {
if( implode("",$value) != '' ) {
if($index && $value) { $search_qry .= " and $index IN ('".implode("','",$value)."') "; }
}
} else {
$value = trim($value);
if($index && $value) { $search_qry .= " and "; $search_qry .= " $index = \"$value\" "; }
}
}
}
return $search_qry;
}
// For String
function getLikeSearchQuery($arr_with_index) {
$search_qry = "";
foreach($arr_with_index as $index => $value) {
$inner_flag = false;
if($index && $value) {
$field_arr = explode(",", $index);
foreach($field_arr as $field_index => $field_value) {
if(!$inner_flag) { $search_qry .= " and ( "; } else { $search_qry .= " or "; }
$value = trim($value);
$search_qry .= " $field_value like "; $search_qry .= " \"%$value%\" ";
$inner_flag = true;
}
}
if($inner_flag) { $search_qry .= " ) "; }
}
return $search_qry;
}
?>

Related

Highligh key words in PHP search result

I have the below code and i am trying to highlight the search keywords on echoing the results. I have tried what is here
and here
but didn't work.
Please where am i getting it wrong.
Below is my code
if (isset($_GET["mainSearch"]))
{
$condition = '';
// $mainSearch = SQLite3::escapeString($_GET['mainSearch']);
$keyword = $_GET['mainSearch'];
$query = explode(" ", $keyword);
foreach ($query as $text)
{
$condition .= "question LIKE '%".SQLite3::escapeString($text)."%' OR ";
}
$condition = substr($condition, 0, -4);
$order = " ORDER BY quiz_id DESC ";
$sql_query = "SELECT * FROM questions WHERE " . $condition . ' '. $order;
$sql_query_count = "SELECT COUNT(*) as count FROM questions WHERE " . $condition .' '. $order;
$result = $db->query($sql_query);
$resultCount = $db->querySingle($sql_query_count);
if ($resultCount > 0)
{
if ($result)
{
while ($row = $result->fetchArray(SQLITE3_ASSOC))
{
//TRYING TO HIGHLIGHT SEARCH KEYWORD HERE.
$wording = str_replace($keyword, "<span style='font-weight: bold;'>".$keyword."</span>", $row['answer']);
echo '<div class="quesbox_3">
<div class="questitle">
<h2>'.$row["question"].'</h2>
</div>
<div class="quesanswer">'.$wording.'</div>
</div>';
}
}
}
else
{
echo "No results found";
}
}
Thank you very much.

PHP advanced search with Multiple OPTION

I am building a search field with php where users can search for Doctors information with multiple search options.
As shown in the picture a user can search by: DR.NAME, SPECIALTY, DIVISION, LOCATION. The DR.NAME should match any keyword and the form doesn't require any fields to be filled out.
This is my current code which isn't working.
doctorsearch.php
<?php
error_reporting(0);
include 'config.php';
$d_fname = $_POST['d_fname'];
$d_spcl = $_POST['d_spcl'];
$d_division = $_POST['d_division'];
$d_location = $_POST['d_location'];
$qry = "SELECT * FROM doctor_reg WHERE ";
if ($d_fname != '') {
$qry .= "d_fname='".mysql_real_escape_string($d_fname)."' AND ";
}
if ($d_spcl != '') {
$qry .= "d_spcl='".mysql_real_escape_string($d_spcl)."' AND ";
}
if ($d_division != '') {
$qry .= "d_division='".mysql_real_escape_string($d_division)."' AND ";
}
if ($d_location != '') {
$qry .= "d_location='".mysql_real_escape_string($d_location)."' AND ";
}
$result = mysql_query($result);
?>
<?php
echo "<table border='1px solid #CCCCCC;' width='100%'>";
echo "<tr style='color:#FFFFFF;background:#555555;'>";
echo "<th style='padding:3px;'>Name</th>";
while($row = mysql_fetch_array($result)){
echo "<tr class='trbd'>";
echo "<td style='padding:3px;'>".$row['d_fname'].' '.$row['d_lname']."</td>";
?>
<?php
echo "</tr>";
}
echo "</table>";
?>
if you want any keyword not exact match then you shoud use like instead of = operator, so change this
if ($d_fname != '') {
$qry .= "d_fname='".mysql_real_escape_string($d_fname)."' AND ";
}
into this
if ($d_fname != '') {
$qry .= "d_fname LIKE'%".mysql_real_escape_string($d_fname)."%' AND ";
}
You need to add OR instead of AND.
Generally, when users search they search by OR condition.
For example: Doctor Name should be Sharma or location should be east street.
If we search with AND conditions, database will search only records who have the exact combination.
AND returns true if all the conditions are true.
OR returns true if any of conditions is true.
Therefore, OR is correct syntax here.
Corrected code:
$qry = "SELECT * FROM doctor_reg";
$searchArray = array();
if ($d_fname != '') {
$searchArray[] = "d_fname LIKE '%".mysql_real_escape_string($d_fname) . "%'";
}
if ($d_spcl != '') {
$searchArray[] = "d_spcl LIKE '%".mysql_real_escape_string($d_spcl) . "%'";
}
if ($d_division != '') {
$searchArray[] = "d_division LIKE '%".mysql_real_escape_string($d_division) . "%'";
}
if ($d_location != '') {
$searchArray[] = "d_location LIKE '%".mysql_real_escape_string($d_location) . "%'";
}
$qry .= ! empty($searchArray) ? " WHERE " . implode(" OR ", $searchArray) : '';

For each results- Mysql - JSON

How i separate the first result of for each loop and remaining. I have 2 divs, i want first result to be displayed there and rest on another div.
Also is there any way that i can get json decode without for each loop, i want to display result based on for each values from database, and querying database in for each loop is not recommended.
Here is my code, What i want
<div class="FirstDiv">
Result1
</div>
<div class="RemDiv">
Remaining result from for each loop
</div>
Here is full code
$data = json_decode($response->raw_body, true);
$i = 0;
foreach($data['photos'][0]['tags'][0]['uids'] as $value) {
if (++$i == 6)
break;
$check = "SELECT fullname FROM test_celebrities WHERE shortname = '$value[prediction]'";
$rs = mysqli_query($con,$check);
if (mysqli_num_rows($rs)==1) //uid found in the table
{
$row = mysqli_fetch_assoc($rs);
$fullname= $row['fullname'];
}
echo 'Celebrity Name: ' . $fullname . '<br/>';
echo 'Similar: ' . $value['confidence']*100 .'%'. '<br/><br/>';
echo "<img src='actors/$value[prediction].jpg'>";
echo "<hr/>";
}
Try this:
$data = json_decode($response->raw_body, true);
$i = 0;
echo '<div class="FirstDiv">'; // add this line here
foreach( $data['photos'][0]['tags'][0]['uids'] as $value ) {
if (++$i == 6) break;
$check = "SELECT fullname FROM test_celebrities WHERE shortname = '$value[prediction]'";
$rs = mysqli_query($con,$check);
if ( mysqli_num_rows($rs) == 1 ) { //uid found in the table
$row = mysqli_fetch_assoc($rs);
$fullname= $row['fullname'];
}
// Echo celebrity information:
echo 'Celebrity Name: ' . $fullname . '<br/>';
echo 'Similar: ' . $value['confidence']*100 .'%'. '<br/><br/>';
echo "<img src='actors/$value[prediction].jpg'>";
echo "<hr/>";
if ($i==1) { echo '</div><div class="RemDiv">'; }; // add this line here
}
echo '</div>'; // close the last tag
$predictions=array();
foreach($data['photos'][0]['tags'][0]['uids'] as $value) {
$predictions[]="'" . mysqli_real_escape_string($con, $value[prediction]) . "'";
}
$check="SELECT fullname FROM test_celebrities WHERE shortname IN (" . implode(',' $predictions) . ")";
$rs = mysqli_query($con,$check);
while ($row = mysqli_fetch_assoc($rs)) {
if (!$count++) {
// this is the first row
}
But note that you now have two sets of data which are sorted differently - hence you'll need to iterate through one and lookup values in the other.

get result on search box

i created a search toolbar on my system i am working, but it does not execute what i am searching, it always return me no results even if the keyword i searched is found on my table in database. pls help me analyze my codes, where i am miss or wrong thnks in advance.
heres my code. 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;
}
}
?>
my table is like this. tbl_student
studId fname mname lname
c-1111 peter jan yu
c-1112 jane trish li
By the look of it you're referencing a column that doesn't exist. Where in your database structure is a column called "keywords"? I don't see it.
From your comment under your original question it seems like you should change
$where .= "`keywords` LIKE '%$keyword%'";
to
$where .= "`studId` LIKE '%$keyword%'";

Give back more than one mysql result in an php class

I'm trying to build my own CMS in classes.
Now I have got a problem when I try to get data from my MySQL database
Instead of one item i'd like to get an collection of all my items
At the end I'd like to get an Object so I can read it out like : $item->id
Here's my code :
static function getContentItems($id, $active, $sort_by, $sort_type, $limit) {
if (isset($id) && !empty($id)) {
$where .= "WHERE id = ".$id;
}
if (isset($active) && !empty($active)) {
$where .= " AND active = ".$active;
}
if (isset($sort_by) && !empty($sort_by)) {
$where .= " ORDER BY ".$sort_by;
if (isset($sort_type) && !empty($sort_type)) {
$where .= " ".$sort_type;
}
}
if (isset($limit) && !empty($limit)) {
$where .= " LIMIT 0,".$limit;
}
if (isset($where) && !empty($where)) {
$query = "SELECT * FROM content ".$where;
} else {
$query = "SELECT * FROM content";
}
$result = mysql_query($query)or die(mysql_error());
$item = new ContentItem();
while ($data = mysql_fetch_array($result)) {
$item->id = $data['id'];
}
return $item;
}
}
dont start your $where string with .
if (isset($id) && !empty($id)) {
$where = "WHERE id = ".$id;
}
and alwez print your $query
Better Solution
if (!empty($id) {
$where = " WHERE id = ".$id;
if (!empty($active)) {
$where .= " AND active = ".$active;
if (!empty($sort_by)) {
$where .= " ORDER BY ".$sort_by;
if (!empty($sort_type)) {
$where .= " ".$sort_type;
}
}
}
}
if (empty($limit)) {
$where .= " LIMIT 0,".$limit;
}
and later
$item = new ContentItem();
$data = array(); $i=0;
while ($data = mysql_fetch_object($result)) {
$search_result[$i] = $data;
$i++;
}
return $search_result;
and any id can be retrieve by $search_result[$i]->id
Why don't you use Arrays?
Like this:
$collection = array();
while ($data = mysql_fetch_array($result)) {
$item = new ContentItem();
$item->id = $data['id'];
$collection[] = $item; //Appends the item to the array
}
return $collection;
You can access your array in this way:
$collection = YourClassName::getContentItems(...);
foreach($collection as $item) {
// do something with each $item
print_r($item);
}
Look into using mysql_fetch_object http://php.net/manual/en/function.mysql-fetch-object.php instead of mysql_fetch_array.. it returns rows the db as an object already

Categories