SQL "LIKE" If empty returns all rows - php

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.

Related

php/mySQL: querying records by id from array?

i want to query several records by id like:
$ids = array(10,12,14,16,....);
the query would be something like:
select * from users where id=10 or id=12 or id=14 or id=16 ..
is it possible to query it in a more comfortable way like (compared to php):
select * from user where in_array(id, array(10,12,14,16))
thanks
You can use IN instead of OR clauses
select * from users where id IN (put_your_array_here)
Example:
select * from users where id IN (10,12,14,16);
Note:
According to the manual for MySQL if the values are constant IN
sorts the list and then uses a binary search. I would imagine that
OR evaluates them one by one in no particular order. So IN is
faster in some circumstances.
Related post
Try this.
$id = array(10,12,14,16,....);
$ids = join("','",$id);
$sql = "select * from user where id IN ('$ids')";
OR
$ids = implode(',', $id);
$sql = "select * from user where id IN ($ids)";
You can do it like that using implode in PHP:
"select * from users where id in '".implode("','", $ids)."'"
Please be sure that your ids are safe though

MySQL return rows where column contains categories defined by array (and add weight to the results)

In my app, the user can type in an indefinite amount of categories to search by. Once the user hits submit, I am using AJAX to call my PHP script to query my DB and return the results that match what the user defined for the categories.
My category column is separated as so for each row: "blue,red,yellow,green" etc.
I have two questions:
How can I pass an array to MySQL (like so: [blue,yellow,green]) and then search for each term in the categories column? If at-least one category is found, it should return that row.
Can MySQL add weight to a row that has more of the categories that the user typed in, therefor putting it further to the top of the returned results? If MySQL cannot do this, what would be the best way to do this with PHP?
Thanks for taking the time and looking at my issue.
For the part 1 you can use the function below:
<?php
function createquery($dataarray){
$query="select * from table where ";
$loop=1;
foreach($dataarray as $data)
{
$query.="col='$data'";
if(count($dataarray)<$loop-1){
$query.=' or ';
}
$loop++;
}
return $query;
}
?>
This will return the long query.
use this some like this:
mysql_query("select * from table where category in (".implode($yourarray,',').")");
1)
Arrays are not passed to a MySQL database. What's past is a query which is a string that tells the database what action you want to preform. An example would be: SELECT * FROM myTable WHERE id = 1.
Since you are trying to use the values inside your array to search in the database, you could preform a foreach loop to create a valid SQL command with all those columns in PHP, and then send that command / query to the database. For example:
$array = array('blue', 'red', 'yellow', 'green');
$sql = "SELECT ";
foreach ($array as $value)
{
$sql .= $value.", ";
}
$sql .= " FROM myTable WHERE id = 1";
IMPORTANT! It is highly recommended to used prepared statements and binding your parameters in order not to get hacked with sql injection!
2)
You are able to order the results you obtained in whichever way you like. An example of ordering your results would be as follows:
SELECT * FROM myTable WHERE SALARY > 2000 ORDER BY column1, column2 DESC

How to echo from MySQL the row that contain a city but also the row that are empty in the same field?

In my code I make use of this query. I want to include in the presentation the rows that have London in the pou field, and also the rows that the user have not selected any town and are empty.
$sql = "SELECT * FROM table WHERE eidos='online' AND pou='London' order by time asc";
I tried to add OR pou='' without luck. How can I do this?
Try
$sql = "SELECT * FROM table WHERE eidos='online' AND (pou='London' OR pou='') order by time asc";

$_SESSION storing wrong value

I made a portal where i have to fetch result with primary key as id i am using it everywhere storing it in a variable however there is a certain problem that i am facing
$sql="SELECT users from hostelusers WHERE users Like'%$roll%'";
$result = mysql_query($sql) or die(mysql_error());
$rows=mysql_fetch_row($result);
$uid=$rows[0];
$_SESSION['uid']=$uid;
In my code the variable $uid is echoing out values of column 1 ie users however I have selected column 0 which is id(in the table in mysql)
can't think of any mistake there
your mysql query string is wrong . You are using :
$sql="SELECT users from hostelusers WHERE users Like'%$roll%'";
And how do you expect to get id field in the result ??
Moreover you will be having only a single column [field] in your rows[] and that is rows[0]
if you want to use rows[0] to get your id field
Change your query to this
$sql="SELECT id from hostelusers WHERE users Like'%$roll%'";
or this:
$sql="SELECT * from hostelusers WHERE users Like'%$roll%'";
and it will work for sure

MySQL PHP Query placed within another query's while loop failing

I have a column of pony names, where the breeder's Prefix is included with the pony's name (eg. Ashbrook Boy, where Ashbrook is the Breeder's Prefix, and Boy is the name of the pony). I have another table where I have a list of all the Prefixes used. I want to cycle through that list, and for each record search through my ponies and fetch those whose names begin with each prefix in turn. When they are fetched, I want to remove the said prefix from their name, and pop it into a column for that purpose on their own table.
In the end, I want -rather than one column with both Prefix and Name mixed in - two columns: one for Prefix, one for Name.
I thought the code below would do it for me, but it's not working. I get a 'not a valid resource' error for $res. Any help you could give me would be hugely appreciated - I really don't want to do this by hand! :P
I'm using a PHP script off a MySQL db, which I can access via PHPMyAdmin.
include '../conn.php';
$q=mysql_query("SELECT DISTINCT Pre FROM prefixes");
while($r=mysql_fetch_array($q)) {
$pre=$r['Pre'];
$sql="SELECT ID, Name FROM profiles WHERE (Name REGEXP '^$pre') ORDER BY ID ASC";
mysql_query($sql);
echo $sql;
while($res=mysql_fetch_array($sql)){
$name=$res['Name'];
$name=trim(str_replace("$pre","", $name));
$id=$res['ID'];
mysql_query("UPDATE profiles SET Prefix = '$pre', Name = '$name' WHERE ID = '$id' ");
}
}
mysql_close($con);
Your mistake come from the fact that $sql is the query string, not the mysql result of the query
$sql="SELECT ID, Name FROM profiles WHERE (Name REGEXP '^$pre') ORDER BY ID ASC";
mysql_query($sql);
echo $sql;
while($res=mysql_fetch_array($sql)){
with this, it will look better :
$sql="SELECT ID, Name FROM profiles WHERE (Name REGEXP '^$pre') ORDER BY ID ASC";
$result = mysql_query($sql);
while($res=mysql_fetch_array($result)){

Categories