How to optimize queries in mysql - php

My mysql query for search is :
$result = mysql_query("SELECT * FROM room_tb WHERE location ='{$location}' AND price BETWEEN '$minprice' AND '$maxprice' ")or die('Could not connect: ' . mysql_error()); ;
This makes a compulsion to enter both the location and min and max price in form.
I want a query that can make user to enter either location or max and min price, as well as allow user to search by both fields. What should i do?

When I am generating my queries with optional fields, I create an array of each field, then join them with implode
$query_array = array();
$queries_stringed = '';
if(strlen($location) > 0){
$query_array[] = "location ='{$location}'";
};
if(strlen($minprice) > 0 && strlen($maxprice) > 0){
$query_array[] = "(price BETWEEN '$minprice' AND '$maxprice')";
};
if(!empty($query_array)){
$queries_stringed = "WHERE ".implode(" AND ", $query_array);
};
$result = mysql_query("SELECT * FROM room_tb $queries_stringed");

Thsi ought to do it for you :
$query = "SELECT * FROM room_tb ";
if($location){
$query .= " WHERE location ='{$location}' ";
}
if(($minprice)&&($maxprice)&&(!$location)){
$query .= " WHERE price BETWEEN '$minprice' AND '$maxprice'";
}
if(($minprice)&&($maxprice)&&($location)){
$query .= " AND price BETWEEN '$minprice' AND '$maxprice'";
}
$result = mysql_query($query)or die('Could not connect: ' . mysql_error());
Cheers

As an addition to those answers - you shouldn't trust users inputs and should escape given strings or use PDO instead of mysql_ functions

Related

PHP filters combining into one SQL query

I'm trying to filter through my database according to filters done by visitors.
$query = "select * from Sheet1 where";
//filter query start
if (!empty($brand)) {
$branddata = implode("','", $brand);
//testing removing query
$query .= " Brand in('$branddata') and";
}
if (!empty($model)) {
$modeldata = implode("','", $model);
//testing removing query
$query .= " Model in('$modeldata') and";
}
/* if(!empty($model) && empty($brand)){
} */
if (!empty($spower) && !empty($epower)) {
$query .= " Power>='$spower' and Power<='$epower' and";
}
if (!empty($sprice) && !empty($eprice)) {
$query .= " Doors>='$sprice' and Doors<='$eprice'";
}
$rs = mysqli_query($conn, $query) or die("Error : " . mysqli_error($conn));
The result I wish to get is a sql query that works and has correct syntax. Such as select * from Sheet1 where Doors>='$sprice' and Doors<='$eprice', if the visitor is filtering by price.
Currently, my code is made so that it simply adds a certain string to the variable. This means that if you don't filter by model, it skips model, because the model variable is empty. The problem comes to if you filter by power, the SQL will become select * from Sheet1 where Power>='$spower' and Power<='$epower' and. Obviously this doesn't work, so I need help in making the code make sure it works for every combination of filters.
Append $query .= " 1 = 1"; at the end. I did some modification in your given code. Have a look.
<?php
$query = "SELECT * FROM `Sheet1` WHERE";
//filter query start
if(!empty($brand)){
$branddata = implode("','",$brand);
$query .= " (Brand in('$branddata')) AND";
}
if(!empty($model)){
$modeldata = implode("','",$model);
$query .= " (Model in('$modeldata')) AND";
}
if(!empty($spower) && !empty($epower)){
$query .= " (Power>='$spower' AND Power<='$epower') AND";
}
if(!empty($sprice) && !empty($eprice)){
$query .= " (Doors>='$sprice' AND Doors<='$eprice') AND"; //Added 'AND'
}
$query .= " 1 = 1"; //Added new line
$rs = mysqli_query($conn,$query) or die("Error : ".mysqli_error($conn));
?>
Add AND on each query appended in if conditions. Then, at last add $query .= " 1 = 1";. Which will save you from extra AND coming at the end. If none of the conditions satisfy, then your query will be SELECT * FROM Sheet1 WHERE 1 = 1. Simple. And, don't forget to differentiate between conditions in query. Differentiate your conditions like how I did by opening and closing brackets.
I would do it this way
$filters=array();
if(!empty($brand)){
$branddata =implode("','",$brand);
//testing removing query
$filters[]= " Brand in('$branddata')";
}
if(!empty($model)){
$modeldata =implode("','",$model);
//testing removing query
$filters[]= " Model in('$modeldata') and";
}
if(!empty($spower) && !empty($epower)){
$filters[]= " Power>='$spower' and Power<='$epower' and";
}
if(!empty($sprice) && !empty($eprice)){
$filters[]= " Doors>='$sprice' and Doors<='$eprice'";
}
$query = "select * from Sheet1 where";
foreach ($filters as $filter) {
$query.=' AND '.$filter;
}
$rs = mysqli_query($conn,$query) or die("Error : ".mysqli_error($conn));

How to put my PHP results into an output variable?

The code below selects rows from the database table but I want to select 10 random rows and put them in an output variable like the code below.Not csv in particular but to imitate the one below.
$result = mysqli_query($dbc, "SHOW COLUMNS FROM customer");
$numberOfRows = mysqli_num_rows($result);
if ($numberOfRows > 0) {
$values = mysqli_query($dbc, "SELECT * FROM customer");
while ($rowr = mysqli_fetch_row($values)) {
for ($j=0;$j<$numberOfRows;$j++) {
$csv_output .= $rowr[$j].", ";
}
$csv_output .= "\n";
}
}
print $csv_output;
exit;
First i want to select ten random rows then output them in something like the code above.
My code:
<?php
DEFINE ('DBUSER', '');
DEFINE ('DBPW', '');
DEFINE ('DBHOST', '');
DEFINE ('DBNAME', '');
$dbc = mysqli_connect(DBHOST,DBUSER,DBPW);
if (!$dbc) {
die("Database connection failed: " . mysqli_error($dbc));
exit();
}
$dbs = mysqli_select_db($dbc, DBNAME);
if (!$dbs) {
die("Database selection failed: " . mysqli_error($dbc));
exit();
}
$query = 'Select * FROM Funsies
Order By Rand()
Limit 5';
$result = mysqli_query($dbc, $query);
?>
SELECT name
FROM random AS r1 JOIN
(SELECT (RAND() *
(SELECT MAX(id)
FROM random)) AS id)
AS r2
WHERE r1.id >= r2.id
ORDER BY r1.id ASC
LIMIT 1
INTO OUTFILE 'c:\\users\\desktop\\file_name.csv'
fields TERMINATED BY ',' enclosed by '"'
LINES TERMINATED BY '\r\n';

Why this simple Query doesn't work?

i can't make it work this simple query,it gives me my "die" error
mysql_select_db("minigest_dev" , $con);
$query = " SELECT * "
. "FROM anag_c_indirizzi"
. "WHERE id_cliente = '1';";
$result = mysql_query($query, $con) or
die("query non valida: ". mysql_error());
where is the mistake?
When your query is concatenated, it becomes SELECT * FROM anag_c_indirizziWHERE id_cliente = '1'. You need to add a space so that it becomes [...] anag_c_indirizzi WHERE [...].
You can try this.
Your mistake that you are show error in or condition.
Note : $query = " SELECT * "
. "FROM anag_c_indirizzi"
. "WHERE id_cliente = '1';";
multiple semicolon not allow in sql plz remove one semicolon(;)
mysql_select_db("minigest_dev" , $con);
$query = " SELECT *
FROM anag_c_indirizzi
WHERE id_cliente = '1'";
$result = mysql_query($query);
if (!$result) {
die('query non valida:' . mysql_error());
}
When you append you need to take care of string. Just give one space WHERE clause starts.
mysql_select_db("minigest_dev" , $con);
$query = " SELECT * "
. " FROM anag_c_indirizzi "
. " WHERE id_cliente = 1;";
$result = mysql_query($query, $con) or
die("query non valida: ". mysql_error());

how to make sql filters efficient php

I have 4 filters for a catalog (name , id, date, price). Those are inputs from the user to see specific data from the database. Those 4 filters are going to produce 4^2 (16) sql_queries on php , because some of the filters may be null. Is there a better way to make queries less ?
example:
if(isset($_POST['filters']))
{
$date = $_POST['date'];
$timi = $_POST['timi'];
$employee = $_POST['dropdown_users'];
$proion =$_POST['dropdown_proionta'];
$query = ("SELECT * FROM id_of_orders WHERE username='$employee' AND price = '$timi' AND time = '$date' AND proion='$proion'");
$result=mysql_query($query);
while($row= mysql_fetch_array($result))
{
echo $row['id_order'] . " " . $row['time'] . '<br>';
}
}
I think you are looking for something like this:
$query = "SELECT * FROM id_of_orders WHERE 1=1";
if(!empty($employee))
$query .= " AND username='$employee'";
if(!empty($timi))
$query .= " AND price='$timi'";
if(!empty($date))
$query .= " AND time='$date'";
if(!empty($proion))
$query .= " AND proion='$proion'";
This way no query conditions are added for empty filters, while entered filters will be used as conditions for the results.

PHP query does not return result

This query is not returning any result as there seems to be an issue with the sql.
$sql = "select region_description from $DB_Table where region_id='".$region_id."' and region_status =(1)";
$res = mysql_query($sql,$con) or die(mysql_error());
$result = "( ";
$row = mysql_fetch_array($res);
$result .= "\"" . $row["region_description"] . "\"";
while($row = mysql_fetch_array($res))
{
echo "<br /> In!";
$result .= " , \"" . $row["region_description"] . "\"";
}
$result .= " )";
mysql_close($con);
if ($result)
{
return $result;
}
else
{
return 0;
}
region_id is passed as 1.
I do have a record in the DB that fits the query criteria but no rows are returned when executed. I beleive the issue is in this part ,
region_id='".$region_id."'
so on using the gettype function in my php it turns out that the datatype of region_id is string not int and thus the failure of the query to function as my datatype in my tableis int. what would be the way to get parameter passed to be considered as an int in php. url below
GetRegions.php?region_id=1
Thanks
Try it like this:
$sql = "SELECT region_description FROM $DB_Table WHERE region_id = $region_id AND region_status = 1"
The region_id column seems to be an integer type, don't compare it by using single quotes.
Try dropping the ; at the end of your query.
First of all - your code is very messy. You mix variables inside string with escaping string, integers should be passed without '. Try with:
$sql = 'SELECT region_description FROM ' . $DB_Table . ' WHERE region_id = ' . $region_id . ' AND region_status = 1';
Also ; should be removed.
try this
$sql = "select region_description from $DB_Table where region_id=$region_id AND region_status = 1";
When you are comparing the field of type integer, you should not use single quote
Good Luck
Update 1
Use this.. It will work
$sql = "select region_description from " .$DB_Table. " where region_id=" .$region_id. " AND region_status = 1";
You do not need the single quotes around the region id i.e.
$sql = "SELECT region_description FROM $DB_Table WHERE region_id = $region_id AND region_status = 1"

Categories