I'm trying to create the search system with mutliple criteria fields. My question is how to handle the empty criteria fields (omitted by user). I need to check what if the variable is empty in order to implement the AND condition. In my case, the last name is required, so I just have to check id first name and ID are not empty fields:
$query ="SELECT first_name, last_name FROM students WHERE last_name ILIKE '%$last_name%' ";
if(isset($_GET['$first_name']))
$condition[]="first_name ILIKE '%$first_name'";
if(isset($_GET['$ID']))
$condition[]="ID = '$ID'";
if(!empty($condition))
$query .= implode(' AND ',$condition);
$result = pg_query($query);
this doesn't work.
i think you are missing an AND
if(!empty($condition))
$query .= ' AND '.implode(' AND ',$condition);
Probably the variables that you are requesting from the GET are wrong, they have a $
symbol after the name.
Also you can print the Query before executing it to see if it well formatted.
Try this and post the result please.
$query ="SELECT first_name, last_name FROM students WHERE last_name ILIKE '%$last_name%' ";
if(isset($_GET['$first_name']))
$condition[]="first_name ILIKE '%$first_name'";
if(isset($_GET['$ID']))
$condition[]="ID = '$ID'";
if(!empty($condition))
$query .= implode(' AND ',$condition);
echo $query; exit();
$result = pg_query($query);
The logic should work, but it seems you have a lack of basic PHP syntax and principles.
I'm guessing you have:
<input type='text' name='ID' />
Not
<input type='text' name='$ID' />
So therefor you should use $_GET['id']
.
The next thing, it seems like you're counting on registered globals which is deprecated in new versions of php.
You should use:
$condition[]="ID = '" . $_GET['ID'] . "'";
You're not escaping income values , use pg_escape_string()
:
$condition[]="ID = '" . pg_escape_string( $connection, $_GET['ID']) . "'";
You're not initializing $conditions
array, add:
$conditions = array();
to the beginning of your script
You're missing AND
when you're building final query:
if( count( $conditions)){
$query .= ' AND ' . implode( ' AND ', $conditions);
}
Or alternatively you can add last_name
to $conditions
:
$query ="SELECT first_name, last_name FROM students WHERE ";
$conditions = array(
"last_name ILIKE '%" .
pg_escape_string($connection, $_GET['last_name']) .
"%'"
);
// ...
$query .= implode( ' AND ', $conditions);
Have a look at Pomm's Where class. It allows you to easily create AND / OR criterias and bind them with values in order to escape them. This way you can use multiple selection lists and join them with an OR clause and join those with other criterias with ANDs.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.