PHP mysql - Empty php variable used in mysql selects all rows - php

I have this variable $search=''; which stores words typed in a search bar and an empty default value. I then execute a query like this:
$result=$conn->query("SELECT * FROM users WHERE name LIKE '%".$search."%'");
But this query returns all rows when the $search variable is empty. And I want it to show "0" row results when it is empty.
This may have no sense at all but, I can't use a method like this:
if(!empty($search)){
$result=$conn->query("SELECT * FROM users WHERE name LIKE '%".$search."%'");
}
I need a method that executes the same query whatever the value of $search is. Is there any other method?

If you change your query, it'll return 0 rows if $search is empty.
$result=$conn->query("SELECT * FROM users WHERE name LIKE '%".$search."%' AND '".$search."' != ''");

Maybe using IF in a WHERE query helps you:
$result=$conn->query("SELECT * FROM users WHERE name LIKE IF ( '%".$search."%' = '%%', '', '%".$search."%')");
in case the search string is empty this will return only the empty names from the table; assuming there are no empty names in the table this will return zero results.

Send an empty array if the search variable is empty.
if(!empty($search)){
$result=$conn->query("SELECT * FROM users WHERE name LIKE '%".$search."%'");
}
else {
$result = [];
}

Related

MySQL select query comma separated numbers filter result

My table look like this:
Table screenshot
Here I'm getting the result by query:
$subject_ids = implode(',', $_POST['subject_ids'])
SELECT * FROM table WHERE focusarea LIKE '%$subject_ids%' ;
The result is perfect, but there is nothing to display when I select more than one subject ids, like if selecting only one then it shows,
but when to select 1, 2, and 4, but there is nothing with this LIKE query...
How can I fix this?
Use implode like,
PHP
$subject_id_aray = explode(",",$_POST['subject_ids']);
$in_array_string = array();
foreach($subject_id_aray as $values){
$in_array_string[] = "'".$values."'";
}
MySql
$sql = "SELECT * FROM table WHERE focusarea in (".implode(",",$in_array_string).") ;";
LIKE clause will not work in your case because using LIKE '%1,2,3%' in query will not get anything, as you as using Ids you should use IN instead of LIKE. LIKE will be used separately for each id if it is string.
As you are getting $_POST['subject_ids'] as an array, query will be like
$subject_str = implode(',', $_POST['subject_ids']);
$sql = "SELECT * FROM table WHERE focusarea IN($subject_str)";
If your column focusarea is not integer then
$subject_str = "'".implode("','", $_POST['subject_ids'])."'";
$sql = "SELECT * FROM table WHERE focusarea IN($subject_str)";
Maybe you have bug in POST.
Try to echo, $subject_ids befor inject to SQL.
You focus are is simple string of numbers, connected by ,, but what you are sending by POST maybe is not correct.
Other problem, this don't look like you full code.
Provide you file, if this don't resolve problem.

MySQL LIKE clause with variables in CodeIgniter

I defined a model and tried to get data from two tables using the UNION keyword. Here I used the LIKE keyword as a constraint. When I use this query without variables (hard-coded variable values), it works. But it doesn't work with variables. Instead it gives an empty array. What's wrong with it?
function searchProf(){
//$name=$this->input->post('name');
$name='du';
$query=$this->db->query("SELECT name FROM users WHERE name like '%".$name."%' UNION SELECT name FROM children WHERE name like '%".$name."%' ");
print_r ($query->result());
}
Change '%".$name."%' to this '%$name%'.
function searchProf(){
//$name=$this->input->post('name');
$name ='du';
$query = $this->db->query("SELECT name FROM users WHERE name like '%$name%' UNION SELECT name FROM children WHERE name like '%$name%' ");
print_r ($query->result());
}
Please use active record base or SQL binding to your SQL queries. Otherwise you have to face for SQL Injections.
`
function searchProf(){
$name ='du';
$sql = "SELECT name FROM users WHERE name like ? UNION SELECT name FROM children WHERE name like ? ";
$query = $this->db->query($sql,array('%'.$name.'%','%'.$name.'%'));
print_r ($query->result());
}

PHP MySQL Query insert Function

Is there any possibilty to add a function-call in a SQL-Query?
At the moment i'm doing this:
§sql = "SELECT * FROM TABLE";
But I want, that I'm using a field from my table and call with this a function, which return me true or false.
Maybe a example could explain it better:
"$sql = SELECT * FROM TABLE WHERE functionCall(TABLE.FIELD)=true";
Then I just get all entrys from TABLE, where my function returns true.
Is there any possibility to do that?
you could use If condition before like that :
$sql = "SELECT * FROM TABLE";
fetch your query here
If(functionCall($row['FIELD'])==true) {
your wished code here
.......
}

SQL "LIKE" If empty returns all rows

Hello I have 2 textboxes and i want to give to the user the option to choose one in order to find results. The user can search through the id or the name. My problem is because i use LIKE%field% when the user chooses to search through the id the name field stays empty and returns all the table rows. I want to have results only if the user enters some value in the textbox. This is my sql query. I'm using mysql
"SELECT * FROM properties WHERE ID='$id' OR Name LIKE '%$name%'"
Thank you all
If the user has to select which field to search, you can do:
if ($_POST['search'] == 'id') {
$sql = "SELECT * FROM properties WHERE ID='$id'"
} else {
$sql = "SELECT * FROM properties WHERE Name LIKE '%$name%'"
}
You can do this in a single query (values are checked from the query itself):
"SELECT * FROM properties WHERE ('$id'='' OR ID='$id') AND ('$name' ='' OR Name LIKE '%$name%')"
Explanation:
First condition:
The query will select records with ID='$id' only when $id is not empty.
If $id is empty, query will not go for the second part ID='$id'
Second condition:
The query filters records with Name LIKE '%$name%' only when $name is not empty.
If $name is empty, query will not go for Name LIKE '%$name%'.
NB: This technique is extremely useful when you have numerous parameters to check, rather than using a bunch of if...elses at php side.

Search suggestion box inputs space in front of search query

We have a problem with our search suggestions. Everytime we click on a suggestion at our website, it puts a space in front of the search query, which causes the query to fail.
The code that we use for the suggestions is this:
$query = $db->query("SELECT DISTINCT productnaam FROM product WHERE merk LIKE '$queryString%' LIMIT 10");
if($query) {
// While there are results loop through them - fetching an Object (i like PHP5 btw!).
while ($result = $query ->fetch_object()) {
// Format the results, im using <li> for the list, you can change it.
// The onClick function fills the textbox with the result.
// YOU MUST CHANGE: $result->value to $result->your_colum
echo '<li onClick="fill(\''.$result->merk.' '.$result->productnaam.'\');">'
.$result->merk.' '.$result->productnaam.''.'</li>';
}
} else {
echo 'ERROR: There was a problem with the query.';
Try out with trim()
$queryString = trim($queryString);
The trim() function removes whitespaces and other predefined characters from both sides of a string.
try the trim() function as Sameera Thilakasiri specified below and also update your query to something like "SELECT DISTINCT productnaam FROM product WHERE merk LIKE '%$queryString%' LIMIT 10" The percent sign on both sides will ensure that your query will select records that contain your input as opposed to records that start with your input.
bellow is some further explanation on the SQL LIKE condition that might help you out
// This query will look for records that start with "sa"
select * from table where name like 'sa%'
// This query will look for records that contain "sa"
select * from table where name like '%sa%'
// This query will look for records that end with "sa"
select * from table where name like '%sa'
hope that helps!

Categories