I want to Filter from MyTable
the way I get as result only the rows corresponding to the checkboxes checked.
(1) <input type="cBox" name="Filter[Table_Column_Name_X]" value="y" />
(2) <input type="cBox" name="Filter[Table_Column_Name_Y]" value="y" />
(3) <input type="cBox" name="Filter[Table_Column_Name_Z]" value="y" />
Ex.:
if 'only' checkbox (1) is checked
I retrieve 'only' the rows WHERE Table_Column_Name_X='y'
if checkbox (1) and if checkbox (3) are checked
I retrieve 'only' the rows WHERE Table_Column_Name_X='y' AND Table_Column_Name_Z='y'
.........and so on foreach checkbox checked!
Something like this
if(isset($_POST['Filter'][]) && !empty($_POST['Filter'][]){
$query= "Select * From MyTable WHERE Table_Columns_Names_Checked='y'";
}
Myabe I should use variables or foreach statement. Any help appreciated.
Your HTML code is incorrect:
<input type="checkbox" name="Filter[]" value="Table_Column_Name_X" />
<input type="checkbox" name="Filter[]" value="Table_Column_Name_Y" />
<input type="checkbox" name="Filter[]" value="Table_Column_Name_Z" />
Your PHP code (following code is untested):
$where = "";
if(isset($_POST['Filter'] ) {
foreach( $_POST['Filter'] as $filter ) {
switch( $filter ) {
case 'Table_Column_Name_X' : if( $where != '' ) $where .= " AND ";
$where .= Table_Column_Name_X = ??????????;
break;
//--- repeat above for other 2 options
}
$sql = "Select * From MyTable";
if( $where != "" ) $sql .= " WHERE " . $where;
//--- do the query
The ????? indicates that the column must have a particular value for the query to work on otherwise it will just return everything and there is no need for the filter.
It is not wise to use table/fieldnames in your HTML as you are exposing the structure of you database to would be hackers. Use numbers instead.
Related
I am working on filter, with php(codeigniter). I have three checkboxes, and I want to search(select query), according to selected checkboxes.
If I fill Type and male, then the query should should look like:
"Select * from tableName where column1='type' and column='gender'"
This should occur dynamically, according to the checkbox selected.
How can I do this using Php ?
Here are my html fields
<input type="checbox" name="type" value="type">
<input type="checbox" name="male" value="male">
<input type="checbox" name="male" value="male">
You have to try something like this
if (isset($_POST) && !empty($_POST)) {
$where = array();
if ($_POST['type'] != "") {
$where['type like'] = $this->input->post('type', TRUE);
}
if ($_POST['male'] != "") {
$where['male like'] = $this->input->post('male', TRUE);
}
}
$data = $this->model->retrieve($where);
Here's my problem: I have a set of inputs that are used to "filter" an SQL table. When Using one "filter" my code works fine, but when I try to use more than one (ie $states and $keywords) it will give me only one filter. In this case only the $states are used. BE AWARE, In the code below I'm using simple strings to test what the (Pseudo) SQL statement is will look like. I need one, or any combination of "filters" to work. I have a feeling my if statements are coming back true prematurely? or maybe just structured wrong?
HTML:
<form id="ask-topics" method="post" action="<?php echo $_SERVER['PHP_SELF']?>">
<div>
<input id="all" type="radio" name="opt" value="all" /><label for="all">ALL documents</label>
<input id="new" type="radio" name="opt" value="new"/><label for="new">NEW documents</label>
</div>
<div>
<input id="keywords" type="text" class="text-box" name="keywords" placeholder="Type keywords..." />
</div>
<div>
<input id="conn" type="checkbox" name="state_chk[0]" class="state-chk" value="CT" /><label for="conn">Conn.</label>
<input id="nh" type="checkbox" name="state_chk[1]" class="state-chk" value="NH"/><label for="nh">N.H.</label>
<input id="nj" type="checkbox" name="state_chk[2]" class="state-chk" value="NJ" /><label for="nj">N.J.</label>
<input id="ny" type="checkbox" name="state_chk[3]" class="state-chk" value="NY"/><label for="ny">N.Y.</label>
<input id="vt" type="checkbox" name="state_chk[4]" class="state-chk" value="VT" /><label for="vt">VT</label>
</div>
<div>
<input name="submit" class="button-link" type="submit" value="submit" />
</div>
PHP/SQL(Pseudo)
if (isset($_POST['submit'])){
$keyword = $_POST['keywords'];
$states = $_POST['state_chk'];
$doc_opt = $_POST['opt'];
$query_filter = "";
$new_query = "Select `some colunms`
FROM `this_table`
LEFT JOIN this_other_table
ON this_other_table.column = this_table.categoryid"; // Add WHERE/ORDER BY after
if ($states){
$query_filter = " A WHERE statement to get state specific documents";
}
elseif($keyword){
$query_filter = "a WHERE statemenrt to filter keywords";
}
elseif($doc_opt == "new"){
$query_filter = " an ORDER BY statement to show only new documents";
}
// USING MULTIPLE FILTERS
elseif($keyword && $doc_opt == "new"){
$query_filter = " a WHERE and ORDER BY statement for getting keywords and new documents";
}
elseif($doc_opt == "new" && $states){
$query_filter = " a WHERE and ORDER BY statement for getting state specific docs and new docs";
}
elseif($keyword && $states){
$query_filter = " a WHERE statement for getting keywords and state specific docs";
}
else{
$query_filter = " a generic WHERE AND ORDER BY statement";
}
echo $new_query.=$query_filter;
}
UPDATED PHP:
// CHECK FOR MULTIPLE FILTERS FIRST!
if ($keyword && $doc_opt == "new" && $states){
$query_filter = " a WHERE/ORDER BY statemenrt to filter all three cases";
}
elseif($keyword && $doc_opt == "new"){
$query_filter = " a WHERE/ORDER BY statemenrt to filter keywords and new documents";
}
elseif($doc_opt == "new" && $states){
$query_filter = " a WHERE/ORDER BY statemenrt to filter new documents by specific states";
}
elseif($keyword && $states){
$query_filter = " a WHERE statemenrt to filter keywords and specific states";
}
elseif($doc_opt == "new" && $states){
$query_filter = " a WHERE/ORDER BY statemenrt for getting state specific new documents";
}
elseif($keyword && $states){
$query_filter = " a WHERE statement for getting keywords in state specific documents";
}
// IF NO MULTIPLE CASES CHECK FOR INDIVIDUAL CASES SECOND!
elseif ($states){
$query_filter = " A WHERE statement to get state specific documents";
}
elseif ($keyword){
$query_filter = "a WHERE statement to filter keywords";
}
elseif ($doc_opt == "new"){
$query_filter = " an ORDER BY statement to show only new documents";
}
// IF NO FILTER INPUTS WERE USED GET A GENERIC SET OF RESULTS LAST!
else{
$query_filter = " a generic WHERE AND ORDER BY statement";
}
If you have elseif it's probably going through one of the first ones and not the multiple. So hence not combining the query together. Placing the multiple first and then the more normal/default last should sort the problem.
FYI I wouldn't be using this to make sql - you should use something like fluentPDO
http://envms.github.io/fluentpdo/
Things like this make your code more secure and a lot easier to make SQL queries.
This seems to be a common question as I have seen plenty of similar questions.
however, none of the answers actually pointing out how to do the selecting from mysql database and this is my issue as the moment.
basically I have a table which I store the search data in it.
it looks like this:
id blond darkHair busty curvy
---------------------------------------------------
1 blond busty
2 dark hair busty curvy
3 blond curvy
4 blond curvy
and I have a form with checkboxes like so:
<form action="search.php" method="post">
<input name="keyword[]" type="checkbox" value="blond" />
<input name="keyword[]" type="checkbox" value="dark hair" />
<input name="keyword[]" type="checkbox" value="busty" />
<input name="keyword[]" type="checkbox" value="curvy" />
</form>
and the PHP codes like this:
if(isset($_POST['keyword']))
{
$keyword = $_POST['keyword'];
foreach ($_POST['keyword'] as $keyword) {
$keywordarray[] = mysqli_real_escape_string($conx, $keyword);
}
$keywords = implode (",", $keywordarray);
$sql = "SELECT * FROM girlsStaff
WHERE (`blond` LIKE '%".$keyword."%') OR (`darkHair` LIKE '%".$keyword."%') OR (`busty` LIKE '%".$keyword."%') OR (`thin` LIKE '%".$keyword."%')" or die();
$query = mysqli_query($conx, $sql);
Now, apart from converting this code to PDO or prepared statement, there is another issue which I don't understand!
it doesn't matter how many chechboxes i select... it always returns the result for last checked/selected checkbox value from mysql database....
is there something that I am missing?
i also, did echo $keywords at the top of my page to see whats being sent to the page and I get the value of all the selected/checked boxes being sent correctly.. so I know the issue is not there.
any help or advice would be appreciated.
You require to build query dynamically.
<?php
$clause = " WHERE ";//Initial clause
$sql="SELECT * FROM `girlsStaff` ";//Query stub
if(isset($_POST['submit'])){
if(isset($_POST['keyword'])){
foreach($_POST['keyword'] as $c){
if(!empty($c)){
$sql .= $clause."`".$c."` LIKE '%{$c}%'";
$clause = " OR ";//Change to OR after 1st WHERE
}
}
}
echo $sql;//Remove after testing
}
?>
<form method="POST" action="#">
<form action="search.php" method="post">
Blond: <input name="keyword[]" type="checkbox" value="blond" />
Dark Hair: <input name="keyword[]" type="checkbox" value="dark hair" />
Busty : <input name="keyword[]" type="checkbox" value="busty" />
Curvy; <input name="keyword[]" type="checkbox" value="curvy" />
<input type="submit" name="submit" value="Submit">
</form>
Sample queries
2 check boxes filled
SELECT * FROM `girlsStaff` WHERE `dark hair` LIKE '%dark hair%' OR `curvy` LIKE '%curvy%'
4 filled
SELECT * FROM `girlsStaff` WHERE `blond` LIKE '%blond%' OR `dark hair` LIKE '%dark hair%' OR `busty` LIKE '%busty%' OR `curvy` LIKE '%curvy%'
I think that small change from $keyword to $keywords will solve your problem :)
Now you are looking for items like your last value from $_POST['keyword'] array.
This line:
$sql = "SELECT * FROM girlsStaff WHERE (`blond` LIKE '%".$keyword."%') OR (`darkHair` LIKE '%".$keyword."%') OR (`busty` LIKE '%".$keyword."%') OR (`thin` LIKE '%".$keyword."%')" or die();
You should also use IN instead of LIKE if you have list aaa, bbb, ccc...., but then you will look for elements that have exactly same string in those fields.
After change to $keywords you will have:
... WHERE (`blond` LIKE '%".$keywords."%')
will also not work due to it will mean:
... WHERE (`blond` LIKE '%aaa,bbb,ccc%')
If you want to use like (if fields in DB only contain strings from array) then I suggest to build your query in foreach loop. Example:
$sql = "SELECT * FROM girlsStaff WHERE ".
foreach ($_POST['keyword'] as $keyword) {
$sql .= "(`blond` LIKE '%".$keyword."%') OR ";
}
//and here cut last four character " OR " part that will be unusefull
Typos:
$keywords = implode (",", $keywordarray);
^--- with an S
WHERE (`blond` LIKE '%".$keyword."%')
^--- without an S
You're stuffing in your original $_POST['keyword'] array. An array in string context is the literal word Array, so your query is actually executing as
WHERE (`blond` LIKE '%Array%')
This question already has an answer here:
Building an SQL query based on checkboxes
(1 answer)
Closed 8 years ago.
I want to build a query form my database depending my checkboxes list.
My checkboxes:
<input type="checkbox" id="searchName" checked> Name
<input type="checkbox" id="searchAddress"> Address
<input type="checkbox" id="searchCompany"> Company
<input type="checkbox" id="searchComments"> Comments
My PHP:
$subQuery='';
if($_POST['searchName']=='true') { $subQuery .= " AND KDX_Name LIKE :KDX_SearchTerm"; }
if($_POST['searchAddress']=='true') { $subQuery .= " OR KDX_PostalAddress LIKE :KDX_SearchTerm"; }
if($_POST['searchCompany']=='true') { $subQuery .= " OR KDX_Company LIKE :KDX_SearchTerm"; }
if($_POST['searchComments']=='true') { $subQuery .= " OR KDX_Comments LIKE :KDX_SearchTerm"; }
My problem:
If the first checkbox is not checked, my query is not working cause it works with OR whereas it must start with AND.
Could you please help ?
Thanks.
You have many mistakes in your code in HTML and in PHP ...
I'll not mention everything here, but this is how I would do this.
<input type="checkbox" name="searchName" checked="checked" />Name
<input type="checkbox" name="searchAddress" />Address
<input type="checkbox" name="searchCompany" />Company
<input type="checkbox" name="searchComments" />Comments
<?php
$fields = array(
'searchName' => 'KDX_Name',
'searchAddress' => 'KDX_PostalAddress',
'searchCompany' => 'KDX_Company',
'searchComments'=> 'KDX_Comments',
);
$cond = array();
foreach ($fields as $form_field => $db_field) {
if (isset($_POST[$form_field])) {
$cond[] = "$db_field LIKE '%'" . mysql_escape($_POST[$form_field]) . "%'";
}
}
$subQuery = implode(' OR ', $cond);
?>
More important are these things:
correct HTML form (not id, but name),
easy to extend PHP (use array for field names),
don't check for $_POST[foo]=='true' which is absolutely wrong,
add conditions in array and at the end use implode to easily concatenate everything together,
escape user input variables to avoid SQL injection attacks.
I was wondering if you could tell me what is wrong with my code or point out where I am going wrong, as I am not able to display any results. $_POST['checkbox'] is an array.
<?
$get_id=$_POST['checkbox'];
if(empty($get_id)) {
echo("<h3>You didn't select anything.</h3>");
} else {
$where[] = sprintf(" id='%s'",$_POST["checkbox"]);
}
$where_str = " WHERE ".implode(" AND ",$where);
$sql = "SELECT * FROM products $where_str";
$result = mysql_query($sql, $link);
echo "<table>";
echo "<tr> <th>Description</th> </tr>";
while($row = mysql_fetch_array($result)) {
echo "<tr><td>";
echo $row['description'];
echo "</td></tr>";
}
echo "</table>";
?>
You should refrain from using short tags <? as they are not supported after PHP 5.4.
You are not connecting to MySQL ($link undefined)
You are using a deprecated API (mysql_). See comments for alternatives (mysqli_ or PDO)
You should use the REQUEST_METHOD index of $_SERVER to determine whether your script has been posted.
if( $_SERVER[REQUESTED_METHOD] == 'POST' && !empty($_POST['checkbox']) ) {
... }
You need to use error handling to check for errors. If you echo $sql; you would see that the checkboxes aren't being populated:
SELECT * FROM products WHERE id=''
Your script is vulnerable to SQL injection. When you switch to current API, use binded parameters.
Is $_POST[checkbox] an array?
sprintf will not work as you intend it to because you are passing the entire $_POST[checkbox] array to it. You would need to iterate through it to format it. (See Ollie's answer)
Example
Assuming your HTML looks like this:
<form method="post" ...>
<input type="checkbox" name="checkbox[]" value="1" />
<input type="checkbox" name="checkbox[]" value="2" />
<input type="checkbox" name="checkbox[]" value="3" />
<input type="submit" name="submit" />
</form>
And all three boxes are checked; it will produce this array:
Array
(
[0] => 1
[1] => 2
[2] => 3
)
Following Collie's loop:
foreach ($_POST['checkbox'] as $checkbox) {
$where[] = sprintf(" id='%s'",$checkbox);
}
$where will look like:
Array
(
[0] => id='1'
[1] => id='2'
[2] => id='3'
)
The rest of your script should work. However, you should look into using the IN operator.
That will enable you to skip the loop and just use implode:
$where = "'" . implode("', '", $_POST[checkbox]) . "'";
Which produces:
'1', '2', '3'
And combined with IN:
$sql = "SELECT ... FROM WHERE id IN ($where)";
Be aware that this is not sanitized and you're still vulnerable to injection.
If $_POST["checkbox"] is an array like you say then you cannot use it as a string in the sprintf. Try using array_pop to return the last value of that array or similar.
You could foreach through each element in the array:
foreach ($_POST['checkbox'] as $checkbox) {
$where[] = sprintf(" id='%s'",$checkbox);
}
Although this will probably just create an invalid SQL statement if asking for ID to be equal to two different integers.