Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple sort using SQL SELECT Query using PHP and Form

Tags:

sql

php

I use a html form with 6 criterias, using $_POST lat's convert criterias in variables like here:

Case 1 - All criterias are default
$core = null; $mhz = null; $ram = null; $cam = null; $mAh = null $screen = null
The correct sql query is this :
$sql = "SELECT * FROM $tbl_name ORDER BY performanta_cpu_core DESC, performanta_cpu DESC, performanta_rami DESC LIMIT $start, $limit";

Case 2 - Only one criteria is set
$core = null; $mhz = "performanta_cpu=1400"; $ram = null; $cam = null; $mAh = null $screen = null
The corect query is this :
$sql = "SELECT * FROM $tbl_name WHERE $mhzz ORDER BY performanta_cpu_core DESC, performanta_cpu DESC, performanta_rami DESC LIMIT $start, $limit";

Case 3 - Here is the problem All or more than one criterias ore setted:
$core = 2; $mhz = "performanta_cpu=1400"; $ram = "performanta_rami=1024"; $cam = "camera_spate=3.2"; $mAh = "baterie_mAh=2250"; $screen = "densitate=441";

I understand that i have need to make "WHERE" to be dinamic and visible just when any variable is set and also I have need an "AND" also dinamically like:

$sql = "SELECT * FROM $tbl_name WHERE $core AND $mhzz ORDER BY performanta_cpu_core DESC, performanta_cpu DESC, performanta_rami DESC LIMIT $start, $limit";
I am stressed for a week with this and i cant advance without help...

Thanks in advance

like image 652
NiTrO Avatar asked Mar 08 '13 22:03

NiTrO


1 Answers

Disclaimer: This is terrible code and there are a million better ways to do this, but, this is the simplest explanation.

$parameters = array();
if(!empty($core)){
$parameters['core'] = $core;
}
if(!empty($mhz)){
$parameters['mhz'] = $mhz;
}
if(!empty($ram)){
$parameters['ram'] = $ram;
}
if(!empty($cam)){
$parameters['cam'] = $cam;
}
if(!empty($mAh)){
$parameters['mAh'] = $mAh;
}
if(!empty($screen)){
$parameters['screen'] = $screen;
}

$sql = "SELECT * FROM $tbl_name WHERE 1=1 ";
foreach($parameters as $k=>$v){
 $sql .= " AND ".$k."='".$v."'";
}
$sql .=  " ORDER BY performanta_cpu_core DESC, performanta_cpu DESC, performanta_rami DESC LIMIT $start, $limit";

// All of those parameters should be sanitized to prevent SQL injection.
// mysql_* is deprecated, use mysqli_* or PDO.
like image 186
Matt Avatar answered Sep 18 '22 16:09

Matt