This question already has an answer here:
I want to build a query form my database depending my checkboxes list.
<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
$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"; }
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.
</div>
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: