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;
?>
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'm currently in the process of creating a very simple search feature for a website in which the user is able to search a database for events using a number of different criteria (from one to many, varied number) and I'm experiencing an issue with the prepared statement I'm using, the bind_param() in particularly.
Here is the relevant PHP code:
...
...
$title = (empty($_POST['eventTitle'])) ? null : $_POST['eventTitle'];
$venue = (empty($_POST['venue'])) ? null : $_POST['venue'];
$catID = (empty($_POST['catID'])) ? null : $_POST['catID'];
$start = (empty($_POST['start'])) ? null : $_POST['start'];
$end = (empty($_POST['end'])) ? null : $_POST['end'];
$price = (empty($_POST['price'])) ? null : $_POST['price'];
include 'database_conn.php';
$sql = 'SELECT eventID, eventTitle, venueID, catID, eventStartDate,
eventEndDate, eventPrice FROM te_events WHERE 1';
$sqlCondition = '';
$bindFirstArg = '"';
$bindSecondArg = '';
if($title !== null && !empty($title)) {
$sqlCondition = $sqlCondition . " AND eventTitle LIKE \"%"
. $title . "%\"";
}
if($venue !== null && $venue !== '0') {
$sqlCondition = $sqlCondition . " AND venueID=?";
$bindFirstArg = $bindFirstArg . "s";
$bindSecondArg = $bindSecondArg . ", " . $venue;
}
if($catID !== null && $catID !== '0') {
$sqlCondition = $sqlCondition . " AND catID=?";
$bindFirstArg = $bindFirstArg . "s";
$bindSecondArg = $bindSecondArg . ", " . $catID;
}
if($start !== null && $start !== '0') {
$sqlCondition = $sqlCondition . " AND eventStartDate=?";
$bindFirstArg = $bindFirstArg . "s";
$bindSecondArg = $bindSecondArg . ", " . $start;
}
if($end !== null && $end !== '0') {
$sqlCondition = $sqlCondition . " AND eventEndDate=?";
$bindFirstArg = $bindFirstArg . "s";
$bindSecondArg = $bindSecondArg . ", " . $end;
}
if($price !== null && !empty($price)) {
$sqlCondition = $sqlCondition . " AND eventPrice=?";
$bindFirstArg = $bindFirstArg . "i";
$bindSecondArg = $bindSecondArg . ", " . $price;
}
$sql = $sql . $sqlCondition;
$bindFirstArg = $bindFirstArg . '"';
$search_stmt = $conn -> prepare($sql);
if (false===$search_stmt) {
die('prepare() failed: ' . htmlspecialchars($conn->error));
}
$search_stmt -> bind_param($bindFirstArg, $bindSecondArg);
$search_stmt -> execute();
$search_stmt -> bind_result($eventIDRes, $eventTitleRes, $venueIDRes,
$catIDRes, $eventStartRes, $eventEndRes, $eventPriceRes);
while ($search_stmt->fetch()) {
printf ("%s %s %s %s %s %s %i\n", $eventIDRes, $eventTitleRes,
$venueIDRes, $catIDRes, $eventStartRes, $eventEndRes, $eventPriceRes);
}
mysqli_stmt_close($search_stmt);
The error I'm receiving states
Warning: mysqli_stmt::bind_param() [mysqli-stmt.bind-param]: Number of elements in type definition string doesn't match number of bind variables in /var/www/vhosts/numyspace.co.uk/web_users/home/~unn_w12019212/public_html/webdev/searchresult.php on line 101"
Any ideas?
You need to pass bind_param a separate argument for each ? in your query, as well as the formats as the first parameter. You can't pass it a comma-separated string, that won't work. It just reads that as the first ? and then complains that you didn't send it the rest.
Also, don't add quotes inside your $bindFirstArg string. bind_param just wants a list of all the data types (i, d, s, or b) , it doesn't want " characters.
What you need to do is push your values into an array, then call bind_param via call_user_func_array.
$sqlCondition = '';
$bindFirstArg = '';
$bindParams = array();
// You need to bind $title as well, otherwise you are wide open to SQL
// injection and have just thrown out the benefits of prepared statements
if($title !== null && !empty($title)) {
$sqlCondition .= " AND eventTitle LIKE ?";
$bindFirstArg .= "s";
// Add the `%` to the value, not the query
$title = "%{$title}%";
// bind_param wants these to be references
$bindParams[] =& $title;
}
// Change all your ifs to look like this.
// They need to push into the $bindParams array
if($catID !== null && $catID !== '0') {
$sqlCondition .= " AND catID=?";
$bindFirstArg .= "s";
// bind_param wants these to be references
$bindParams[] =& $catID;
}
// etc...
$sql .= $sqlCondition;
$search_stmt = $conn->prepare($sql);
// Call bind_param with the correct number of parameters
array_unshift($bindParams, $bindFirstArg);
// This will make sure the parameters are passed correctly.
// Each variable needs to be passed as a separate parameter
call_user_func_array(array($search_stmt, 'bind_param'), $bindParams);
$search_stmt->execute();
$search_stmt->bind_result($eventIDRes, $eventTitleRes, $venueIDRes,
$catIDRes, $eventStartRes, $eventEndRes, $eventPriceRes);
while ($search_stmt->fetch()) {
printf ("%s %s %s %s %s %s %i\n", $eventIDRes, $eventTitleRes,
$venueIDRes, $catIDRes, $eventStartRes, $eventEndRes, $eventPriceRes);
}
$search_stmt->close();
I'm having a syntax issue with this bit of code:
$query = "SELECT *
FROM ".$db->nameQuote('#__mls')."
WHERE 1=1"
. if ($zip != null)
{ AND ".$db->nameQuote('MSTZIP')." = ".$db->quote($zip)."}
. if ($city != null)
{ AND ".$db->nameQuote('MSTCITY')." = '".$db->quote($city)."'}
. if ($bdrms != null)
{ AND ".$db->nameQuote('MSTBDRMS')." >= ".$db->quote($bdrms)."}
. if ($bths != null)
{ AND ".$db->nameQuote('MSTBATHS')." >= ".$db->quote($bths)."}
. if ($lprice != null)
{ AND ".$db->nameQuote('MSTLISTPRC')." BETWEEN ".$db->quote($lprice)." AND ".$db->quote($hprice)."}
";"
;
First string " starts the query statement, second " layer assigns the table, when the WHERE statement, then it gets tricky. All the if statements are messing with me. I feel like that's where a " is getting misplaced or missing.
Utterly broken beyond belief. Try something more like this:
$query = "SELECT * FROM " . $db->nameQuote('#__mls') . " WHERE 1=1";
$clauses = array();
if ($zip != null) {
$clauses[] = $db->nameQuote('MSTZIP') . " = " . $db->quote($zip);
}
if (etc...) {
...
}
$query .= implode(' AND ', $clauses);
echo $query;
Before every AND you are missing " , you need to build your query in different manner (please double check every ' I am sure I missed few somewhere)
$query = "SELECT *
FROM ".$db->nameQuote('#__mls')."
WHERE 1=1";
if ($zip != null)
{ $query .= " AND ".$db->nameQuote('MSTZIP')." = '".$db->quote($zip)."'";}
if ($city != null)
{$query .= " AND ".$db->nameQuote('MSTCITY')." = '".$db->quote($city)."'";}
if ($bdrms != null)
{$query .= " AND ".$db->nameQuote('MSTBDRMS')." >= '".$db->quote($bdrms)."'";}
if ($bths != null)
{$query .= " AND ".$db->nameQuote('MSTBATHS')." >= '".$db->quote($bths)."'";}
if ($lprice != null)
{$query .= " AND ".$db->nameQuote('MSTLISTPRC')." BETWEEN '".$db->quote($lprice)." AND ".$db->quote($hprice).";}
;
I've made this php code for filtering the results from a mysql database. It works very well, but I'm sure this is not the most efficient way (or proper use of the language) to achieve the desired results. I'm trying my best to get "good" at writing code and would appreciate some feedback on how I could do this better.
$filter = "";
if (isset($_POST['submit']))
{
$aircraft_reg = "";
$prefix = "";
$part_number = "";
$flight_control = "";
if(!empty($_POST['aircraft_reg']))
{
$aircraft_reg = "aircraft_reg = '" . $_POST['aircraft_reg'] . "'";
}
if(!empty($_POST['prefix']))
{
$prefix = "prefix = '" . $_POST['prefix'] . "'";
}
if(!empty($_POST['part_number']))
{
$part_number = "part_number = '" . $_POST['part_number'] . "'";
}
if(!empty($_POST['flight_control']))
{
$flight_control = "flight_control = '" . $_POST['flight_control'] . "'";
}
if ($aircraft_reg != "" && ($prefix != "" || $part_number != "" || $flight_control != ""))
{
$a = " AND ";
}
else
{
$a = "";
}
if ($prefix != "" && ($part_number != "" || $flight_control != ""))
{
$b = " AND ";
}
else
{
$b = "";
}
if ($part_number != "" && $flight_control != "")
{
$c = " AND ";
}
else
{
$c = "";
}
if ($aircraft_reg != "" || $prefix != "" || $part_number != "" || $flight_control != "")
{
$filter = "WHERE " . $aircraft_reg . $a . $prefix . $b . $part_number . $c . $flight_control;
}
}
$result = mysql_query("SELECT * FROM installed $filter ORDER BY aircraft_reg , part_number, date_installed ASC");
You only need follow this pattern:
$result = mysql_query("
SELECT *
FROM installed
WHERE
".($_POST['aircraft_reg']?"aircraft_reg=" .mysql_real_escape_string($_POST['aircraft_reg']):"1" )." AND
...
ORDER BY aircraft_reg , part_number, date_installed ASC");
another alternative:
foreach($_POST as $key => $val)
if($key!="submit" and $val)
$filters[] = "$key='".mysql_real_escape_string($val)."' ";
$result = mysql_query("
SELECT *
FROM installed
".(isset($filters)?"WHERE ".implode("AND ",$filters):"")."
ORDER BY aircraft_reg , part_number, date_installed ASC");
I suggest you using something well-established such as ActiveRecord:
http://www.phpactiverecord.org/
No need to re-invent the wheel (unless this is purely for learning, in which case, carry on!)
... in the case this is purely for learning, don't forget to escape any REQUEST data such as those $_POSTs that you're using, with something like mysql_real_escape_string
Quick:
Use array_key_exists to see if something is in $_POST
Do not put $_POST values directly in your SQL, escape them. More info when you Google for SQL injection attack
I would validate/sanitize your input first, and then create the query in one go:
if (array_key_exists("partnumber", $_POST) {
$part_number = validate_partnumber($_POST['partnumber']);
$part_number = escape_for_db($part_number);
}
$q = ".... WHERE part_number='$part_number' ....";
Other than that, it doesn't look too bad.
You can try this, as conditional operator has less time complexity than if()-else(). Moreover less use of variables will cause less memory allocation, hence it is faster and more optimized than the one you used.
Another thing, using mysql_real_escape_string() prevent sql injection.
$filter = "";
if (isset($_POST['submit']))
{
$condition_count = 0;
if(!empty($_POST['aircraft_reg']))
{
$filter = " WHERE aircraft_reg = '" . mysql_real_escape_string($_POST['aircraft_reg']) . "'";
$condition_count++;
}
if(!empty($_POST['prefix']))
{
$condition_count > 0?$filter .= " AND prefix = '" . mysql_real_escape_string($_POST['prefix']) . "'":$filter .= " WHERE prefix = '" . mysql_real_escape_string($_POST['prefix']) . "'";
$condition_count++;
}
if(!empty($_POST['part_number']))
{
$condition_count > 0?$filter .= " AND part_number = '" . mysql_real_escape_string($_POST['part_number']) . "'":$filter .= " WHERE part_number = '" . mysql_real_escape_string($_POST['part_number']) . "'";
$condition_count++;
}
if(!empty($_POST['flight_control']))
{
$condition_count > 0?$filter .= " AND flight_control = '" . mysql_real_escape_string($_POST['flight_control']) . "'":$filter .= " WHERE flight_control = '" . mysql_real_escape_string($_POST['flight_control']) . "'";
$condition_count++;
}
}
$result = mysql_query("SELECT * FROM installed ".$filter." ORDER BY aircraft_reg , part_number, date_installed ASC");
if (!isset($_POST['submit'])) exit;
$aircraft_reg = $_POST['aircraft_reg'];
$prefix = $_POST['prefix'];
$part_number = $_POST['part_number'];
$flight_control = $_POST['flight_control'];
$result = mysql_query("
SELECT *
FROM installed
where
aircraft_reg = if('$aircraft_reg' = '', aircraft_reg, '$aircraft_reg')
and
prefix = if('$prefix' = '', prefix, '$prefix')
and
part_number = if('$part_number' = '', part_number, '$part_number')
and
flight_control = if('$flight_control' = '', flight_control, '$flight_control')
ORDER BY aircraft_reg , part_number, date_installed
");
If this is for real then don't forget to sanitize the user input or you will be an easy sql injection victim.
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) . ')';
}