I have form like this:
<form method="POST" action="<?php echo base_url() ?>admin/admin_search">
<fieldset>
<label for="nalozi">Nalozi</label><input type="checkbox" name="nalozi" />
<label for="malio_glasi">Mali oglasi</label><input type="checkbox" name="mali_oglasi" />
<label for="zute_strane">Zute strane</label><input type="checkbox" name="zute_strane" />
<label for="berza_rada">Berza rada</label><input type="checkbox" name="berza_rada" />
<label for="vesti">Vesti</label><input type="checkbox" name="vesti" />
<label for="event">Dogadjaji</label><input type="checkbox" name="event" />
</fieldset>
<input type="search" name="keyword" id="keyword" />
<input type="submit" value="Trazi"/>
</form>
and PHP code for searching:
function admin_search(){
$keyword = trim($_POST['keyword']);
$search_explode = explode(" ", $keyword);
$x = 0;
$mgs = isset($_POST['mali_oglasi']) ? 1 : "";
$jbs = isset($_POST['berza_rada']) ? 2 : "";
$nws = isset($_POST['vesti']) ? 3 : "";
$ypg = isset($_POST['zute_strane']) ? 4 : "";
if($mgs != "" || $jbs != "" || $nws != "" || $ypg != ""){$or = " OR ";}else{$or = "";}
if($jbs != "" || $nws != "" || $ypg != "" ){$or1 = " OR ";}else{$or1 = "";}
if($nws != "" || $ypg != "" ){$or2 = " OR ";}else{$or2 = "";}
if($ypg != "" ){$or3 = " OR ";}else{$or3 = "";}
$nlz = isset($_POST['nalozi']) ? "person" : "";
$dgj = isset($_POST['event']) ? "event" : "";
if($nlz != "" || $dgj != ""){$z = ", "; $or_like = " OR "; }else{$z = " "; $or_like = "";}
if($dgj != ""){$z1 = ", ";$or_like1 = " OR ";}else{$z1 = " ";$or_like1 = "";}
if($mgs != "" || $ypg != "" || $jbs != "" || $nws != ""){$gi = "global_info";}else{$gi = "";}
$sql = "SELECT * FROM ";
if($gi != ""){$sql .= " $gi $z";}
if($nlz != ""){$sql .= " $nlz $z1";}
if($dgj != ""){$sql .= " $dgj";}
$sql .= " WHERE ";
if($mgs != ""){$sql .= " global_info.info_type_id = {$mgs} $or1 ";}
if($jbs != ""){$sql .= " global_info.info_type_id = {$jbs} $or2 ";}
if($nws != ""){$sql .= " global_info.info_type_id = {$nws} $or3 ";}
if($ypg != ""){$sql .= " global_info.info_type_id = {$ypg} ";}
$sql .= " AND ";
foreach($search_explode as $each){
$x++;
if($x == 1){
if($gi != ""){$sql .= " global_info.name LIKE '%$each%' $or_like ";}
if($nlz != ""){$sql .= " $nlz.name LIKE '%$each%'$or_like1 ";}
if($dgj != ""){$sql .= " $dgj.name LIKE '%$each%' ";}
} else {
$sql .= " AND global_info.name LIKE '%$each%' ";
}
}
echo $sql;
$q = $this->db->query($sql);
echo $q->num_rows();
return $q = $q->num_rows() == 0 ? FALSE : $q->result_array();
}
Idea behind this search - I must be able to choose witch tables I want to search and the search by the keyword(s) need to work for any table choosen.
When one of the checkboxes is checked, it is working fine, but if two or more are checked, and if there is more than one keyword (for the moment I am trying just global_info table with two or more keywords), function is working fuzzy. Sometimes it does not work, or if it is working it is giving same results multiple times, or everything except the keyword. At the moment I don't quite understand why it is giving results that it is giving. How to make this work?
Try changing it to read like this:
$tables = array();
if(isset($_POST['mali_oglasi'])){
$tables['mgs'] = 1;
}
/*
repeat for the other tables
*/
/* Where you're building your WHERE clause, use this instead of the 'OR' logic */
if(!empty($tables)){
$sql .= 'global_info.info_type_id IN (' . implode(',',$tables) . ')';
}
Related
I need help with my PDO prepared statements.
I know my code is not sanitized and is probably open to a lot of hell, but first I need to overcome this error before I can move on to sanitize my code.
I am trying to write a prepared statement with the WHERE clause, and somehow it keeps giving me an error that I am using a string for a type boolean. But what boolean??
I added a few vardumps before the error. It is in the counting part of my code.
After which, I would also take some pointers on how to make prepared statements out of user input.
I know, it is dangerous, but perhaps I can sanitize all the inner_join, outer_join etc into allowed table names using a in_array after a database table and column name check.
The reason I need to allow this user input is that I am making a website where people can make their own queries to the database and retrieve whatever info they need. But they should only be able to SELECT. Not UPDATE or DROP!
<?php
// Select existing
require_once('ajaxDBQuery.php');
if(!isset($included)) {
$_GET = json_decode($_GET["json"], true);
} else {
$_GET = json_decode($json, true);
}
class GET extends ajaxDBQuery
{
function __construct() {
parent::__construct($_GET['db']);
// ------------------------------------------------
$page = 0;
if (isset($_GET['offset']) && !empty($_GET['offset'])) {
$page = filter_var($_GET['offset'], FILTER_SANITIZE_NUMBER_INT);
}
$per_page = 20;
if (isset($_GET['limit']) && !empty($_GET['limit'])) {
$per_page = filter_var($_GET['limit'], FILTER_SANITIZE_NUMBER_INT);
}
if(isset($_GET['where']) && !empty($_GET['where'])) {
$sqlcount = "SELECT count(*) AS total_records FROM {$_GET['from']['table']} WHERE :test";
$statement = $this->conn->prepare($sqlcount);
var_dump($sqlcount);
var_dump($statement);
var_dump($_GET['where']);
$statement->bindParam(':test', $_GET['where'], PDO::PARAM_STR);
$statement->execute();
} else {
$sqlcount = "SELECT count(*) AS total_records FROM {$_GET['from']['table']}";
$statement = $this->conn->prepare($sqlcount);
$statement->execute();
}
$row = $statement->fetch();
$total_records = $row['total_records'];
$total_pages = ceil($total_records / $per_page);
$offset = ($page) * $per_page;
// ------------------------------------------------
$sql = "SELECT ";
for($i = 0; $i < count($_GET['select']['columns']); $i++) {
if($i == 0) {
$sql .= "{$_GET['select']['columns'][$i]}";
} else {
$sql .= ", {$_GET['select']['columns'][$i]}";
}
}
//{$_GET['select']['columns'][0]}
$sql .= " FROM {$_GET['from']['table']}";
(isset($_GET['from']['as']) && ($_GET['from']['as']) !== "") ? $sql .= " AS {$_GET['from']['as']}" : $sql .= "";
(isset($_GET['inner_join']['table']) && ($_GET['inner_join']['table']) !== "") ? $sql .= " INNER JOIN {$_GET['inner_join']['table']}" : $sql .= "";
(isset($_GET['inner_join']['as']) && ($_GET['inner_join']['as']) !== "") ? $sql .= " AS {$_GET['inner_join']['as']}" : $sql .= "";
if(isset($_GET['inner_join']['on']) && ($_GET['inner_join']['on']) !== "") {
for($i = 0; $i < count($_GET['inner_join']['on']); $i++) {
if($i == 0) {
$sql .= " ON {$_GET['inner_join']['on'][$i]}";
} else {
$sql .= " AND {$_GET['inner_join']['on'][$i]}";
}
}
}
(isset($_GET['left_join']['table']) && ($_GET['left_join']['table']) !== "") ? $sql .= " LEFT JOIN {$_GET['left_join']['table']}" : $sql .= "";
(isset($_GET['left_join']['as']) && ($_GET['left_join']['as']) !== "") ? $sql .= " AS {$_GET['left_join']['as']}" : $sql .= "";
if(isset($_GET['left_join']['on']) && ($_GET['left_join']['on']) !== "") {
for($i = 0; $i < count($_GET['left_join']['on']); $i++) {
if($i == 0) {
$sql .= " ON {$_GET['left_join']['on'][$i]}";
} else {
$sql .= " AND {$_GET['left_join']['on'][$i]}";
}
}
}
(isset($_GET['left_outer_join']['table']) && ($_GET['left_outer_join']['table']) !== "") ? $sql .= " LEFT OUTER JOIN {$_GET['left_outer_join']['table']}" : $sql .= "";
(isset($_GET['left_outer_join']['as']) && ($_GET['left_outer_join']['as']) !== "") ? $sql .= " AS {$_GET['left_outer_join']['as']}" : $sql .= "";
if(isset($_GET['left_outer_join']['on']) && ($_GET['left_outer_join']['on']) !== "") {
for($i = 0; $i < count($_GET['left_outer_join']['on']); $i++) {
if($i == 0) {
$sql .= " ON {$_GET['left_outer_join']['on'][$i]}";
} else {
$sql .= " AND {$_GET['left_outer_join']['on'][$i]}";
}
}
}
(isset($_GET['where']) && ($_GET['where']) !== "") ? $sql .= " WHERE {$_GET['where']}" : $sql .= "";
(isset($_GET['order_by']) && ($_GET['order_by']) !== "") ? $sql .= " ORDER BY {$_GET['order_by']}" : $sql .= "";
(isset($_GET['direction']) && ($_GET['direction']) !== "") ? $sql .= " {$_GET['direction']}" : $sql .= "";
(isset($_GET['limit']) && ($_GET['limit']) !== "") ? $sql .= " LIMIT {$_GET['limit']}" : $sql .= "";
(isset($_GET['offset']) && ($_GET['offset']) !== "") ? $sql .= " OFFSET ".$_GET['offset'] * $_GET['limit']."" : $sql .= "";
$statement = $this->conn->prepare($sql);
$statement->execute();
// ------------------------------------------------
// set the resulting array to associative
$result = $statement->setFetchMode(PDO::FETCH_ASSOC);
$jsonArray = array();
//$jsonArray["totalrecords"] = $total_records;
$jsonArray["totalrecords"] = 1;
while ( ($row = $statement->fetch(PDO::FETCH_ASSOC) ) !== false) {
$jsonArray[] = $row;
}
// ------------------------------------------------
$this->return($jsonArray);
// ------------------------------------------------
}
private function return($jsonArray) {
header('Content-Type: application/json');
echo json_encode($jsonArray);
}
}
$query = new GET();
?>
OUTPUT:
string(56) "SELECT count(*) AS total_records FROM cb_cat WHERE :test"
object(PDOStatement)#3 (1) {
["queryString"]=>
string(56) "SELECT count(*) AS total_records FROM cb_cat WHERE :test"
}
string(27) "systemgrp BETWEEN 10 AND 19"
<br />
<b>Fatal error</b>: Uncaught PDOException: SQLSTATE[22P02]: Invalid text representation: 7 ERROR: invalid input syntax for type boolean: "systemgrp BETWEEN 10 AND 19" ...
I am building a search field with php where users can search for Doctors information with multiple search options.
As shown in the picture a user can search by: DR.NAME, SPECIALTY, DIVISION, LOCATION. The DR.NAME should match any keyword and the form doesn't require any fields to be filled out.
This is my current code which isn't working.
doctorsearch.php
<?php
error_reporting(0);
include 'config.php';
$d_fname = $_POST['d_fname'];
$d_spcl = $_POST['d_spcl'];
$d_division = $_POST['d_division'];
$d_location = $_POST['d_location'];
$qry = "SELECT * FROM doctor_reg WHERE ";
if ($d_fname != '') {
$qry .= "d_fname='".mysql_real_escape_string($d_fname)."' AND ";
}
if ($d_spcl != '') {
$qry .= "d_spcl='".mysql_real_escape_string($d_spcl)."' AND ";
}
if ($d_division != '') {
$qry .= "d_division='".mysql_real_escape_string($d_division)."' AND ";
}
if ($d_location != '') {
$qry .= "d_location='".mysql_real_escape_string($d_location)."' AND ";
}
$result = mysql_query($result);
?>
<?php
echo "<table border='1px solid #CCCCCC;' width='100%'>";
echo "<tr style='color:#FFFFFF;background:#555555;'>";
echo "<th style='padding:3px;'>Name</th>";
while($row = mysql_fetch_array($result)){
echo "<tr class='trbd'>";
echo "<td style='padding:3px;'>".$row['d_fname'].' '.$row['d_lname']."</td>";
?>
<?php
echo "</tr>";
}
echo "</table>";
?>
if you want any keyword not exact match then you shoud use like instead of = operator, so change this
if ($d_fname != '') {
$qry .= "d_fname='".mysql_real_escape_string($d_fname)."' AND ";
}
into this
if ($d_fname != '') {
$qry .= "d_fname LIKE'%".mysql_real_escape_string($d_fname)."%' AND ";
}
You need to add OR instead of AND.
Generally, when users search they search by OR condition.
For example: Doctor Name should be Sharma or location should be east street.
If we search with AND conditions, database will search only records who have the exact combination.
AND returns true if all the conditions are true.
OR returns true if any of conditions is true.
Therefore, OR is correct syntax here.
Corrected code:
$qry = "SELECT * FROM doctor_reg";
$searchArray = array();
if ($d_fname != '') {
$searchArray[] = "d_fname LIKE '%".mysql_real_escape_string($d_fname) . "%'";
}
if ($d_spcl != '') {
$searchArray[] = "d_spcl LIKE '%".mysql_real_escape_string($d_spcl) . "%'";
}
if ($d_division != '') {
$searchArray[] = "d_division LIKE '%".mysql_real_escape_string($d_division) . "%'";
}
if ($d_location != '') {
$searchArray[] = "d_location LIKE '%".mysql_real_escape_string($d_location) . "%'";
}
$qry .= ! empty($searchArray) ? " WHERE " . implode(" OR ", $searchArray) : '';
In form user need to check options who will receive newsletter, for example:
<input type="checkbox" name="male" value="1" />
<input type="checkbox" name="female" value="1" />
<input type="checkbox" name="person" value="1" />
<input type="checkbox" name="company" value="1" />
But I have problem how to create query for db with checked options
I have this code so far, but it is not good, because newsletter need to be 1 all the time and after that I have OR, because when I put AND I don't get the results that I need:
if($options['male']) {
$sqlAddMale = " OR gender = 2 ";
}
if($options['female']) {
$sqlAddFemale = " OR gender = 1 ";
}
if($options['person']) {
$sqlAddPerson = " OR VAT = '' ";
}
if($options['company']) {
$sqlAddCompany = " OR VAT <> '' ";
}
$query = "
SELECT email FROM users WHERE newsletter=1
".$sqlAddMale."
".$sqlAddFemale."
".$sqlAddPerson."
".$sqlAddCompany."
";
I think You need something like this:
$placeOr = false;
if($options['male']) {
$placeOr = true;
$sqlAddMale = " (newsletter=1 AND gender = 2) ";
}
if($options['female']) {
$sqlAddFemale = (($placeOr)?" Or ":"");
$sqlAddFemale .= " (newsletter=1 AND gender = 1) ";
$placeOr = true;
}
if($options['person']) {
$sqlAddPerson = (($placeOr)?" Or ":"");
$sqlAddPerson .= " (newsletter=1 AND VAT = '') ";
$placeOr = true;
}
if($options['company']) {
$sqlAddCompany = (($placeOr)?" Or ":"");
$sqlAddCompany .= " (newsletter=1 AND VAT <> '') ";
$placeOr = true;
}
$query = "
SELECT email FROM users WHERE
".$sqlAddMale."
".$sqlAddFemale."
".$sqlAddPerson."
".$sqlAddCompany."
";
Here is how you can solve your issue, use one variable to build up your where clause, use AND operater when you are adding the first condition, else use OR
$sqlString = '';
if($options['male']) {
$sqlString = " AND gender = 2 ";
}
if($options['female']) {
if(!$sqlString) $sqlString = " AND gender = 1 ";
else
$sqlString .= " OR gender = 1 ";
}
if($options['person']) {
if(!$sqlString) $sqlString = " AND VAT = '' ";
else
$sqlString .= " OR VAT = '' ";
}
if($options['company']) {
if(!$sqlString) $sqlString = " AND VAT <> '' ";
else
$sqlString .= " OR VAT <> '' ";
}
$query = "SELECT email FROM users WHERE newsletter=1'".$sqlString."'";
I have a page with 3 input fields, to search a database. But not all users are going to fill in all fields, so I need a way to make sure the database is checked fine.
Now, I wrote 8 different sql-statements, and with if-statements I check which fields are filled out. This works, but I do feel there must be a better to do this.
ID's in the search form are found in other tables in my database and loaded with jQuery's autocomplete.
Code now used:
<form action="" method="post">
<div class="ui-widget">
<section>
<label for="tags">Trefwoord:</label>
<input name="tags" id="tags"><input type="hidden" name="tags_id" class="tags_id" value="">
</section>
<section>
<label for="categorie">Categorie:</label>
<input name="cats" id="categorie"><input type="hidden" name="cats_id" class="cats_id" value="">
</section>
<section>
<label for="competentie">Competentie:</label>
<input name="com" id="competentie"><input type="hidden" name="com_id" class="com_id" value="">
</section>
<input type="submit" name="submit">
</div>
</form>
<?php
if(isset($_POST['submit'])) {
$trefwoord_id = $_POST['tags_id'];
$categorie_id = $_POST['cats_id'];
$p_trefwoord = $_POST['tags'];
$p_categorie = $_POST['cats'];
$competentie_id = $_POST['com_id'];
$p_comptentie = $_POST['com'];
if($trefwoord_id == null) {$sql = "SELECT * FROM spel_cat LEFT JOIN spel_com ON spel_cat.spelid = spel_com.spelid WHERE '$categorie_id' = catid && '$competentie_id' = comid";}
if($categorie_id == null) {$sql = "SELECT * FROM spel_tw LEFT JOIN spel_com ON spel_tw.spelid = spel_com.spelid WHERE '$trefwoord_id' = twid && '$competentie_id' = comid";}
if($competentie_id == null) {$sql = "SELECT * FROM spel_tw LEFT JOIN spel_cat ON spel_tw.spelid = spel_cat.spelid WHERE '$trefwoord_id' = twid && '$categorie_id' = catid";}
if($trefwoord_id == null && $categorie_id == null) {$sql = "SELECT * FROM spel_com WHERE '$competentie_id' = comid";}
if($trefwoord_id == null && $competentie_id == null) {$sql = "SELECT * FROM spel_cat WHERE '$categorie_id' = catid";}
if($categorie_id == null && $competentie_id == null) {$sql = "SELECT * FROM spel_tw WHERE '$trefwoord_id' = twid";}
if($trefwoord_id == null && $competentie_id == null && $categorie_id == null) {$sql = ""; echo "<b>Gebruik minstens 1 zoekterm</b>";}
if($trefwoord_id != null && $categorie_id != null && $competentie_id != null) {$sql = "SELECT * FROM (spel_tw LEFT JOIN spel_cat ON spel_tw.spelid = spel_cat.spelid) LEFT JOIN spel_com ON spel_cat.spelid = spel_com.spelid WHERE '$trefwoord_id' = twid && '$categorie_id' = catid && '$competentie_id' = comid";
}
if($sql != null) {
$games = mysqli_query($link,$sql) or die(mysql_error());
$num = mysqli_num_rows($games);
// AND SO ON...
WORKING CODE (thanks to OrangeHippo)
<?php
if(isset($_POST['submit'])) {
$trefwoord_id = $_POST['tags_id'];
$categorie_id = $_POST['cats_id'];
$p_trefwoord = $_POST['tags'];
$p_categorie = $_POST['cats'];
$competentie_id = $_POST['com_id'];
$p_comptentie = $_POST['com'];
$from = array();
$where = " 1 = 1 ";
if($trefwoord_id != null) {
$from["str"] = "spel_tw str";
$where .= " AND twid = '$trefwoord_id' ";
}
if($categorie_id != null) {
$from["sca"] = "spel_cat sca";
if (isset($from["str"])) {
$where .= " AND sca.spelid = str.spelid ";
}
$where .= " AND catid = '$categorie_id' ";
}
if($competentie_id != null) {
$from["sco"] = "spel_com sco";
if (isset($from["str"])) {
$where .= " AND sco.spelid = str.spelid ";
}else if (isset($from["sca"])) {
$where .= " AND sco.spelid = sca.spelid ";
}
$where .= " AND comid = '$competentie_id' ";
}
$sql = "SELECT * FROM " . implode(",", $from) . " WHERE $where";
if($trefwoord_id == null && $competentie_id == null && $categorie_id == null) {$sql = ""; echo "<b>Gebruik minstens 1 zoekterm</b>";}
//echo $sql;
if($sql != null) {
$games = mysqli_query($link,$sql) or die(mysql_error());
$num = mysqli_num_rows($games);
//AND SO ON ...
Ideally you would construct the query depending on the values that are passed:
$from = array();
$where = " 1 = 1 ";
if($trefwoord_id != null) {
$from["str"] = "spel_tw str";
$where .= " AND twid = '$trefwoord_id' ";
}
if($categorie_id != null) {
$from["sca"] = "spel_cat sca";
if (isset($from["str"])) {
$where = " AND sca.spelid = str.spelid ";
}
$where .= " AND catid = '$categorie_id' ";
}
if($competentie_id != null) {
$from["sco"] = "spel_com sco";
if (isset($from["str"])) {
$where = " AND sco.spelid = str.spelid ";
}else if (isset($from["sca"])) {
$where = " AND sco.spelid = sca.spelid ";
}
$where .= " AND comid = '$competentie_id' ";
}
$query = "SELECT * FROM " . implode(",", $from) . " WHERE $where";
As you see this way you have a lot less of text, making the code cleaner. If you want to have the code even more clean you can look to use some query builder library like doctrine2 DBAL
i am having this problem and I am trying to come up with the best and most efficient solution. I have a php website with 19 different inputs, all of them are optional and I am using the get method. With those inputs, i have to find the information that matches the data base and return it. The problem I am having is creating the query that will work.
$query = "SELECT * FROM TEST.table";
if(($_GET['Transmission_Line_Designation'] ==="") && ($_GET['Switch_Number'] === "") && ($_GET['Telecom_Circuit_Number'] === "")
&& ($_GET['Transmitter_Frequency'] === "") && ($_GET['Receiver_Frequency'] === "") && ($_GET['power_level'] === "")
&& ($_GET['Phase'] === "") && ($_GET['Modulate'] === "") && ($_GET['trap_type'] === "") && ($_GET['line_tuner_type'] === ""))
//checks if there were no input, if there werent any, display all columns and rows from the data base
{
}
else
{
This is where i'm having the problem, if the users inputs the first input, it will work , however, if the user leaves the first input blank, the query that comes out is "where and" something something, I was thinking about using a lot of if loops to check conditions and add a flag but I am pretty sure there is an easier way to do it.
$query.= " where ";
if
$query .= ($_GET['Transmission_Line_Designation'] === "") ? '' : 'Line_Designation = "'.$_GET['Transmission_Line_Designation'].'"';
$query .= ($_GET['Switch_Number'] === "") ? '' : ' and Switch_Number = "'.$_GET['Switch_Number'].'"';
$query .= ($_GET['Telecom_Circuit_Number'] === "") ? '' : ' and Telecom_Circuit_Number = "'.$_GET['Telecom_Circuit_Number'].'"';
$query .= ($_GET['Transmitter_Frequency'] === "") ? '' : ' and Transmitter_Frequency = "'.$_GET['Transmitter_Frequency'].'"';
$query .= ($_GET['Receiver_Frequency'] === "") ? '' : ' and Receiver_Frequency = "'.$_GET['Receiver_Frequency'].'"';
$query .= ($_GET['power_level'] === "") ? '' : ' and power = "'.$_GET['power_level'].'"';
$query .= ($_GET['Voltage'] === "") ? '' : ' and voltage = "'.$_GET['Voltage'].'"';
$query .= ($_GET['Phase'] === "") ? '' : ' and Phase= "'.$_GET['Phase'].'"';
$query .= ($_GET['Modulate'] === "") ? '' : ' and Modulate = "'.$_GET['Modulate'].'"';
$query .= ($_GET['trap_type'] === "") ? '' : ' and trap = "'.$_GET['trap_type'].'"';
$query .= ($_GET['line_tuner_type'] === "") ? '' : 'and ltunner = "'.$_GET['line_tuner_type'].'"';
echo $query;
}
Thank you guys for your help in advance, i appreciate it.
Throw in a dummy boolean expression first, so that all of your other criteria can start with "AND". Like this:
$query.= " where 1=1 ";
if
$query .= ($_GET['Transmission_Line_Designation'] === "") ? '' : 'AND Line_Designation = "'.$_GET['Transmission_Line_Designation'].'"';
$query .= ($_GET['Switch_Number'] === "") ? '' : ' and Switch_Number = "'.$_GET['Switch_Number'].'"';
$query .= ($_GET['Telecom_Circuit_Number'] === "") ? '' : ' and Telecom_Circuit_Number = "'.$_GET['Telecom_Circuit_Number'].'"';
$query .= ($_GET['Transmitter_Frequency'] === "") ? '' : ' and Transmitter_Frequency = "'.$_GET['Transmitter_Frequency'].'"';
$query .= ($_GET['Receiver_Frequency'] === "") ? '' : ' and Receiver_Frequency = "'.$_GET['Receiver_Frequency'].'"';
$query .= ($_GET['power_level'] === "") ? '' : ' and power = "'.$_GET['power_level'].'"';
$query .= ($_GET['Voltage'] === "") ? '' : ' and voltage = "'.$_GET['Voltage'].'"';
$query .= ($_GET['Phase'] === "") ? '' : ' and Phase= "'.$_GET['Phase'].'"';
$query .= ($_GET['Modulate'] === "") ? '' : ' and Modulate = "'.$_GET['Modulate'].'"';
$query .= ($_GET['trap_type'] === "") ? '' : ' and trap = "'.$_GET['trap_type'].'"';
$query .= ($_GET['line_tuner_type'] === "") ? '' : 'and ltunner = "'.$_GET['line_tuner_type'].'"';
echo $query;
}
What's the problem use if? And loop?
100% sure it will better to maintaince than this code....
try:
foreach($_GET as $key=>$value){
if($value !== '')
switch($key){
case "Modulate":
dosomething();
break;
}
}
It'll much better to maintaince.
Try the below, added some checking too.
<?php
$sql = "SELECT * FROM table WHERE ";
$count = count($_GET);
if ($count) { // check if $_GET has any values at all
foreach ($_GET as $key => $value) {
if ($value) { // check if $value not empty
$sql .= $key . " = " . "'" . $value . "', ";
}
}
$sql = rtrim($sql, ", ");
}
echo $sql;
?>