PHP MYSQL While LOOP not displaying all rows - php

I'm trying to select all the rows from my database, where 'street' is LIKE the contents from an array ($streets).
Here's what I have...
#TEXT AREA INPUT = $streets
$sql = "SELECT * FROM `data` WHERE `street` LIKE '%".implode("%' OR `street` LIKE '%",$streets)."%'";
echo $sql;
$result = mysqli_query($con,$sql) or die(mysql_error());
$totalitems1 = mysqli_num_rows($result);
echo $totalitems1 . "<br>";
while($row = mysqli_fetch_array($result))
{
echo $row['street']. "<br>";
}
the varible $streets is exploded from a text area input, each value on a new line.
When I process this using PHP, only the rows that are LIKE the last 'OR' are returned .. (The last line in the text area). But when I copy and paste the generated SQL into PHPMYADMIN, it returns ALL the data, as expected.
What am I missing here? Thanks.

My guess would be that you aren't stripping the newline from the end of each $street entry, therefore only the last entry looks valid as it probably doesn't have a trailing newline. No doubt your query probably looks like...
SELECT * FROM `data` WHERE `street` LIKE '%foo
%' OR `street` LIKE '%bar
%' OR `street` LIKE '%baz%'
The quick fix would be to use...
implode("%' OR `street` LIKE '%", array_map(function($s) use ($con) {
return $con->escape_string(trim($s));
}, $streets))
Ideally, you should be using a prepared statement with parameter binding.

Related

Auto complete suggestion box are not working properly?

code:
<?php
include('config.php');
$return_arr = array();
$term = $_GET['term'];
$term = str_replace('.','',$term);
$sql = "SELECT * FROM submission where keyword like '%".$term."%' or companyname like '%".$term."%' ORDER BY CASE WHEN keyword LIKE '%".$term."%' THEN 1
ELSE 2 END";
$r = mysqli_query($link,$sql);
while($row = mysqli_fetch_assoc($r))
{
$key = explode(",", $row['keyword']);
foreach ($key as $keyword)
{
$return_arr[] = $keyword;
}
}
echo json_encode($return_arr);
?>
In my code I have created a auto complete suggestion box and its working but it always showing wrong result if I write (i) it always show result with (a) alphabet why not (i) and also want to search with short name. So, How can I do this ?Please help me.
Thank You
if you want to compare result start with input character then remove % from beginning
$sql = "SELECT * FROM submission where keyword like '".$term."%' or companyname
like '".$term."%' ORDER BY CASE WHEN keyword LIKE '".$term."%' THEN 1
ELSE 2 END";
You used %$term% in your query. So whether the data store the searched keyword anywhere in the string, it will display to you. So if you want to search the data start with a specific character remove % from the start of your query to make it as $term% as
$sql = "SELECT * FROM submission where keyword like '".$term."%' or companyname
like '".$term."%' ORDER BY CASE WHEN keyword LIKE '".$term."%' THEN 1
ELSE 2 END";

using LIKE in Sql in PHP web page

I have the code below to search for the text 'english' anywhere in the field language. I've tried formatting the code from SQL into a web PHP page but it doesn't display any information. When I run the sql version select language from media where language like '%english%' it works.
$result = mysql_query("SELECT `language` FROM `media` WHERE `language` LIKE \'%english%\'");
while ($row = mysql_fetch_array($result)) {
echo $row[''];
echo ' ' , $row['language'];
echo '<br />';
}
Don't escape the single quotes around your search term.
$result = mysql_query("SELECT `language` FROM `media` WHERE `language` LIKE '%english%'");
You don't need to escape the ''s. It should just work. So try this:
$result = mysql_query("SELECT `language` FROM `media` WHERE `language` LIKE '%english%'");

sql select where like statement with many OR operands

I am trying to write a simple search function that reads in a string $query.
my question is, can I use multiple ORs in a select statement? I am trying to search one string to see if it matches many column values, then print those rows.
function search($query) {
try {
$db = db_open();
$sql = "select * from pms where (name like :query) or (state like :query) or
(start like :query) or (finish like :query) ";
$statement = $db->prepare($sql);
$statement->bindValue(':query', $query);
$statement->execute();
$pms = $statement->fetchAll();
} catch(PDOException $e) {
die("Error: ".$e->getMessage());
}
return $pms;
}
This is not working, except when i search for a state.
Thanks
For sure.
SELECT * FROM pms WHERE (name LIKE :query) OR (start LIKE :query) OR (finish LIKE :query)
Should work just fine.
1) use backtick in table nam eand column names.
2) use bracket for each or for more clear understanding
3)if you are not using binding then use wildcat (%) with quotes .
try like this:
$sql = "select * from `pms`
where (`name` like '%query%')
OR (`state` like '%query%')
OR (`start` like '%query%')
OR (`finish` like '%query%') ";

php searching multiple fields on msql and return exactly answer

my be i may change the question explanation since no any help,But I real want help.
I have a search box in my form which enable user to search student data in mysql table, I only succeed on searching single field eg (first name or second name or sir name) the BIG problem to me is how to search multiple field on the same text input field or any number of text input field eg(text1, text2, text3) only I want is to have exactly result. Sorry if any mistake.
Here the php codes I use to get single field search.
<html>
<head></head>
<body><input type="text" name="query" value=""/>
<input name="submit" type="submit" value="Search" />
<?php
$query="query";
//mysql_connect
$query='query';
if (isset($_GET['query']))
{
$query=$_GET['query'];
// Instructions if $_POST['value'] exist
}
$raw_results = mysql_query("SELECT * FROM stdreg_exam
WHERE (`fname` LIKE '%".$query."%') or (`secname` LIKE '%".$query."%')or
(`date` LIKE '%".$query."%') or (`surname` LIKE '%".$query."%')") or
die(mysql_error());
$raw_results2 = mysql_query("SELECT(idnumber) FROM student
WHERE (`fname` LIKE '%".$query."%') or (`secname` LIKE
'%".$query."%') or (`date` LIKE '%".$query."%')or
(`surname` LIKE '%".$query."%')") or die(mysql_error());
// * means that it selects all fields, you can also write: `id`, `title`, `text`
// articles is the name of our table
// '%$query%' is what we're looking for, % means anything, for example if $query is Hello
// it will match "hello", "Hello man", "gogohello", if you want exact match use `title`='$query'
// or if you want to match just full word so "gogohello" is out use '% $query %' ...OR ... '$query %' ... OR ... '% $query'
if(mysql_num_rows($raw_results) > 0){
// if one or more rows are
returned do following
while($results = mysql_fetch_array($raw_results)){
while($results2 = mysql_fetch_array($raw_results2)){
// $results = mysql_fetch_array($raw_results) puts data from database into
array, while it's valid it does the loop
echo "<table width='750' height='5' cellpadding='2'
cellspacing='0' border='0'>";
echo"<tr><td>Std_id</td><td>Mathematics</td><td>English</td>
<td>Kiswahili</td><td>Geograph</td><td>Ict</td><td>Science</td>
<td>History</td><td>Pds</td><td>V skill</td><td>French</td>
<td>Religion</td><td>Civics</td>";
echo "<h4> ".$results['exam_name']." Examination result for
" .$results['fname']." " .$results['secname']
." ".$results['surname']." ".$results['class']." Class"."
held on</p>".$results['date']."<hr><th>"; echo"<tr>";
echo ""."<td>".$results2['idnumber'].""."<td>".$results['mathematics']."%"."
<td>".$results['english']."%"."<td>".$results['kiswahili']."%"."
<td>".$results['geograph']."%"."<td>".$results['ict']."%"."
<td>".$results['science']."%"."<td>".$results['history']."%"."
<td>".$results['pds']."%"."<td>".$results['vskill']."%"."
<td>".$results['french']."%"."<td>".$results['religion']."%"."
<td>".$results['civics']."%"."</td></p>";echo"</table>";
//posts results gotten from database(title and text) you can also show id
($results['id'])
}
}
}
else{
// if there is no matching rows do following
echo "No such information in School database";
}
}
else{
// if query length is less than minimum
echo "Enter more strings!!!Minimum length is ".$min_length; "Charactes";
}
?>
If you have 3 text fields, let's say text1, text2 and text3 and you need to get search result from DB. You could try something like this
$query = "SELECT your_feilds,another_fields FROM your_table WHERE 1=1 ";
if($_POST['text1'])
$query .= " AND text1_field like '%$_POST['text1']%' ";
if($_POST['text2'])
$query .= " AND text2_field like '%$_POST['text2']%' ";
if($_POST['text3'])
$query .= " AND text3_field like '%$_POST['text3']%' ";
$result = mysql_query($query);
The above answer from #Shafeeq is very functional and is working as I have used the same approach for one of my applications, but there is one issue, if you have a another field let us say date and you want to search between two dates.
The query will be like that
if($_POST['from_date'] && $_POST['To_date'])
$query .= " AND date between '$from_field' AND '$To_field' ";
Then It does not work for other fileds

PHP err if mysql command gives a result

I have this query
$DB->query("SELECT id FROM tfilter WHERE '". $Properties['Title'] ."' LIKE CONCAT('%', filter, '%')");
I need it to do so that the scrip dies if it gets a result, right now i have this :
if($DB->record_count() != 0) {
$Err = '<b>This cant be uploaded</b>';
include(SERVER_ROOT . '/sections/upload/upload.php');
die();
if($DB->record_count() != 0) {
Should this be something els? Because it dosnt die, even though i KNOW its got a result
This query looks like this in the phpscript. Its part of a bigger site
$DB->query("SELECT id FROM tfilter WHERE '". $Properties['Title'] ."' LIKE CONCAT('%', filter, '%')");
if($DB->record_count() != 0) {
$Err = '<b>This cant be uploaded</b>';
include(SERVER_ROOT . '/sections/upload/upload.php');
die();
$Properties['Title'] = String from the upload script that contains the titel.
$DB is the call til mysql
filter = the row in mysql
tfilter = the database name
WHAT DO I NEED:
I need the php to search the the tabel TFILTER in the row FILTER for matches to $Properties['Title'] and if it finds any then DIE. If the string: The.White.Tiger. exist in FILTER row, og the $Properties['Title'] contains The.White.Tiger.In.The.Yard, the the php should DIE.
I think your query needs to be (repace the single quotes around $Properties['Title'] with backtick):
$DB->query("SELECT id FROM filter WHERE `". $Properties['Title'] ."` LIKE CONCAT('%', filter, '%')");
Also, you don't need to use the concat function to prepend and append % character, you can simply use it as follows:
$DB->query("SELECT id FROM filter WHERE `". $Properties['Title'] ."` LIKE '%{$filter}%'");
could you not use
rowCount() ?
so it should look something like this:
$stmt = $DB->query("SELECT id FROM tfilter WHERE '". $Properties['Title'] ."' LIKE CONCAT('%', filter, '%')");
$numrows=$stmt->rowCount();
$error= $stmt->errorInfo();
echo $error[2];
if($numrows) {
$Err = '<b>This cant be uploaded</b>';
include(SERVER_ROOT . '/sections/upload/upload.php');
die();

Categories