Forming a query string from multiple checkboxes - php

I'm trying to form a query string from multiple checkboxes that will be used to query my database.
I have the following form:
<fieldset data-role="controlgroup">
<input type="checkbox" name="wheat" id="checkbox-1a" class="custom" />
<label for="checkbox-1a">Wheat Allergy</label>
<input type="checkbox" name="yeast" id="checkbox-2a" class="custom" />
<label for="checkbox-2a">Yeast Allergy</label>
<input type="checkbox" name="sugar" id="checkbox-3a" class="custom" />
<label for="checkbox-3a">Sugar Allergy</label>
<input type="checkbox" name="dairy" id="checkbox-4a" class="custom" />
<label for="checkbox-4a">Dairy Allergy</label>
My PHP code is as follows:
if(isset($_POST['wheat']))
{
$str1 = 'wheatfree = 1';
}
if(isset($_POST['yeast']))
{
$str2 = 'yeastfree = 1';
}
if(isset($_POST['sugar']))
{
$str3 = 'sugarfree = 1';
}
if(isset($_POST['dairy']))
{
$str4 = 'dairyfree = 1';
}
$fullsearch = $str1.$str2.$str3.$str4;
$str_SQL = "SELECT * FROM recipes WHERE ".$fullsearch;
echo $str_SQL;
This is sort of doing what I require, but it's not very graceful.
For one, the sql query looks like this:
SELECT * FROM recipes WHERE sugarfree = 1dairyfree = 1
and if users choose not to select one I of course get an Undefined variable error for the str that hasn't been selected.
Not really sure how to fix this or where to go next. I'd like some logic in here that just amended the string based on what is checked on the form which then forms a nice clean SQL query I can run against my DB. But alas i'm lost :(
Help?

Further to Dave's answer:
$options = Array();
$ingredients = Array('wheat', 'yeast', 'sugar', 'dairy');
foreach ($ingredients as $i)
if (isset($_POST[$i]))
$options[] = $i . 'free = 1';
$sql = "SELECT * FROM recipes";
if (count($options))
$sql .= " WHERE " . implode(' AND ', $options);
echo $sql;
But why aren't you using the value property of checkboxes?
<input type="checkbox" name="ingredients[]" value="wheat" />
<input type="checkbox" name="ingredients[]" value="sugar" />
etc.
Then:
$options = Array();
foreach ($_POST['ingredients'] as $i)
$options[] = $i . 'free = 1'; // don't forget to escape $i somehow!
$sql = "SELECT * FROM recipes";
if (count($options))
$sql .= " WHERE " . implode(' AND ', $options);
echo $sql;

How about this:
$options = array();
if(isset($_POST['wheat']))
{
$options[] = 'wheatfree = 1';
}
if(isset($_POST['yeast']))
{
$options[] = 'yeastfree = 1';
}
if(isset($_POST['sugar']))
{
$options[] = 'sugarfree = 1';
}
if(isset($_POST['dairy']))
{
$options[] = 'dairyfree = 1';
}
$fullsearch = implode(' AND ', $options);
$str_SQL = "SELECT * FROM recipes";
if ($fullsearch <> '') {
$str_SQL .= " WHERE " . $fullsearch;
}
echo $str_SQL;

Related

SQL query for data filtering

I have 6 input fields
<input type="text" class="form-control filter-width namef" placeholder="Product Name">
<input type="text" class="form-control filter-width brandf" placeholder="Brand Name">
<input type="text" class="form-control filter-width catf" placeholder="Category">
<input type="text" class="form-control filter-width sizef" placeholder="Size">
<input type="text" class="form-control filter-width pricef" placeholder="Price">
<input type="text" class="form-control filter-width invf" placeholder="Inventory">
each field is used to filter data. if all fields are filled then it is easy to querying data but I actually don't know using how many fields a user is going to filter. He may filter the data using only name, name and brand name, name and brand name and size, price and inventory. putting conditions using if, elseif and thinking of all possible combinations would be difficult and lengthy task.
is there any way to achieve this.
Here's my PHP:
$name = $_REQUEST['name'];
$brand = $_REQUEST['brand'];
$cat = $_REQUEST['cat'];
$size = $_REQUEST['size'];
$price = $_REQUEST['price'];
$inv = $_REQUEST['inv'];
if(!empty($name) AND !empty($brand) AND !empty($cat) AND !empty($size) AND !empty($price) AND !empty($inv) ||){
$sql = "SELECT * FROM products WHERE pname='$name' AND brand_name ='$brand' AND ptype = '$cat' AND psize= '$size' AND sprice = '$price' AND inventory='$inv'";
}
else{
}
$result = $conn->query($sql);
if($result->num_rows>0){
while($row=$result->fetch_assoc()){
$pid = $row['pid'];
$pname = $row['pname'];
$pbrand = $row['brand_name'];
$pcat = $row['ptype'];
$pinv = $row['inventory'];
$pprice = $row['sprice'];
$psize = $row['psize']; ?>
<tr id="<?php echo $pid; ?>" class="prod-details"><?php echo "<td>".$pid."</td><td>".$pname."</td><td>".$pbrand."</td>"."<td>".$pcat."</td>"."<td>".$psize."</td>"."<td>".$pprice."</td>"."<td>".$pinv."</td>"; ?></tr> <?php
}
}
Now I don't know what conditions to think and write inside else body
Try following code
<?php
$sql = "SELECT * FROM products WHERE 1=1 AND ";
foreach ($_REQUEST as $key => $value) {
$columnName = '';
switch ($key) {
case 'name':
$columnName = 'pname';
break;
case 'brand':
$columnName = 'brand_name';
break;
case 'cat':
$columnName = 'ptype';
break;
case 'cat':
$columnName = 'psize';
break;
case 'size':
$columnName = 'ptype';
break;
case 'inv':
$columnName = 'inventory';
break;
}
if (!empty($columnName) && !empty($value)) {
$sql .= " $columnName='$value' AND";
}
}
$sql = rtrim($sql, 'AND');
$result = $conn->query($sql);
if($result->num_rows>0){
while($row=$result->fetch_assoc()){
$pid = $row['pid'];
$pname = $row['pname'];
$pbrand = $row['brand_name'];
$pcat = $row['ptype'];
$pinv = $row['inventory'];
$pprice = $row['sprice'];
$psize = $row['psize']; ?>
<tr id="<?php echo $pid; ?>" class="prod-details"><?php echo "<td>".$pid."</td><td>".$pname."</td><td>".$pbrand."</td>"."<td>".$pcat."</td>"."<td>".$psize."</td>"."<td>".$pprice."</td>"."<td>".$pinv."</td>"; ?></tr> <?php
}
}
Also please correct me if I am wrong.
You could aggregate your query string. You may try the following-
$query = "";
if (!empty($name)) {
$query += " AND pname='$name'";
}
if (!empty($brand)) {
$query += " AND brand_name ='$brand'";
}
if (!empty($cat)) {
$query += " AND ptype = '$cat'";
}
if (!empty($size)) {
$query += " AND psize= '$size'";
}
if (!empty($price)) {
$query += " AND sprice = '$price'";
}
if (!empty($inv)) {
$query += " AND inventory='$inv'";
}
if($query != ""){
$sql = "SELECT * FROM products WHERE 1=1" . $query;
}else{
}

sql search with 2 or more fields

Created an sql search query with having multiple fields I created using if else condition it is working fine but if 1 and 2nd field is emty and 3rd field is not then it dies not work just because of OR keyword please advise how I would be able to correct this
<form method="POST" action="search.php?action=go">
<li>
<h3>Player</h3>
<input type="text" class="form-control" placeholder="Dylan Scout" name="playername" value="<?php if(isset($_POST["playername"])) {echo $_POST["playername"];} ?>">
</li>
<li>
<h3>Age</h3>
<input type="text" class="form-control" placeholder="25" name="age" value="<?php if(isset($_POST["age"])) {echo $_POST["age"];} ?>">
</li>
<li>
<h3>Country</h3>
<input type="text" class="form-control" placeholder="Wallabies" name="country" value="<?php if(isset($_POST["country"])) {echo $_POST["country"];} ?>">
</li>
<li>
<h3>Club</h3>
<input type="text" class="form-control" placeholder="Eagle" name="club" value="<?php if(isset($_POST["club"])) {echo $_POST["club"];} ?>">
</li>
<li>
<button type="submit" name="search">Search</button>
</li>
</form>
And here is my sql php query
<?php
if(isset($_GET["action"]) == 'go') {
$stmt = "SELECT * FROM users WHERE";
if($_POST["playername"]) {
$stmt .= " OR fname LIKE '%".$_POST["playername"]."%' OR lname LIKE '%".$_POST["playername"]."%'";
}
if($_POST["age"]) {
$stmt .= " OR age LIKE '%".$_POST["age"]."%' ";
}
if($_POST["country"]) {
$stmt .= " OR country LIKE '%".$_POST["country"]."%' ";
}
if($_POST["club"]) {
$stmt .= " OR club LIKE '%".$_POST["club"]."%' ";
}
} else {
$stmt = "SELECT * FROM users ";
}
echo $stmt . "<br />";
$sql = mysqli_query($connection, $stmt);
?>
Please let me know how would I be able to make it work properly as if i write on 3rd fields and leave other fields empty then it will become asWHERE OR which will become obviously wrong query and won't work
Thank You
The function implode will help you.
Add them into an array and connect them after.
<?php
$array = array();
if (isset($_POST["playername"]))
$array[] = "fname LIKE '%".$_POST["playername"]."%' OR lname LIKE '%".$_POST["playername"]."%";
if (isset($_POST["age"]))
...
$stmt = "SELECT * FROM users";
if (count($array) > 0)
$stmt .= " WHERE " . implode(" OR ",$array);
$sql = mysqli_query($connection, $stmt);
?>
Try this. Using implode() you can achieve this.
<?php
if(isset($_GET["action"]) == 'go') {
$where = array();
if($_POST["playername"]) {
$where[] = " OR fname LIKE '%".$_POST["playername"]."%' OR lname LIKE '%".$_POST["playername"]."%'";
}
if($_POST["age"]) {
$where[] = " OR age LIKE '%".$_POST["age"]."%' ";
}
if($_POST["country"]) {
$where[] = " OR country LIKE '%".$_POST["country"]."%' ";
}
if($_POST["club"]) {
$where[] = " OR club LIKE '%".$_POST["club"]."%' ";
}
if(!empty($where))
{
$stmt = "SELECT * FROM users WHERE " . implode(" AND ", $where) ." ";
}
else
{
$stmt = "SELECT * FROM users ";
}
} else {
$stmt = "SELECT * FROM users ";
}
echo $stmt . "<br />";
$sql = mysqli_query($connection, $stmt);
?>
add where condition to an array, and next use implode function, for example:
<?php
if(isset($_GET["action"]) == 'go') {
$stmt = "SELECT * FROM users";
if($_POST["playername"]) {
$where[] = "fname LIKE '%".$_POST["playername"]."%' OR lname LIKE '%".$_POST["playername"]."%'";
}
if($_POST["age"]) {
$where[] = "age LIKE '%".$_POST["age"]."%' ";
}
if($_POST["country"]) {
$where[] = "country LIKE '%".$_POST["country"]."%' ";
}
if($_POST["club"]) {
$where[] = "club LIKE '%".$_POST["club"]."%' ";
}
if(count($where))
$stmt .= " WHERE " . implode(" OR ", $where);
echo $stmt . "<br />";
$sql = mysqli_query($connection, $stmt);
?>

PHP Multiple input search

I'm currently working on a bit of PHP and I've 3 text inputs. The values are searched in the MySQL database and should return whatever amount of results correspond with the entered criteria.
here is the search form:
<form id='SearchPersonal' method='post' action='businessUsersSearch.php' accept-charset='UTF-8'>
<fieldset >
<legend>Search</legend>
<div class='container'>
<label for='C_Name' >Business Name: </label><br/>
<input type='text' name='C_Name' id='C_Name' maxlength="50" /><br/>
<label for='C_County' >City: </label><br/>
<input type='text' name='C_County' id='C_County' maxlength="50" /><br/>
<label for='Job_Type' >Job Type: </label><br/>
<input type='text' name='Job_Type' id='Job_Type' maxlength="50" /><br/>
</div>
<div class='container'>
<input type='submit' name='Submit' value='Search' />
</div>
</fieldset>
</form>
Here is the PHP script it links too in the action:
<?php
$mysqli_link = mysqli_connect("server", "database", "pass", "user");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_POST['submit'])) {
// define the list of fields
$fields = array('C_Name', 'C_County', 'Job_Type');
$conditions = array();
// loop through the defined fields
foreach($fields as $field){
// if the field is set and not empty
if(isset($_POST[$field]) && $_POST[$field] != '') {
// create a new condition while escaping the value inputed by the user (SQL Injection)
$conditions[] = "'$field' LIKE '%" . mysqli_real_escape_string($mysqli_link, $_POST[$field]) . "%'";
}
}
// builds the query
$query = "SELECT C_Name, C_StreetNumber, C_StreetName, C_Postcode, C_County, C_Tele, C_Website, Contact_Forename, Contact_Surname, Contact_Email, Jobs.Job_Type, Jobs.Job_Price FROM Company INNER JOIN Jobs ON Company.Company_ID = Jobs.Company_ID";
// if there are conditions defined
if(count($conditions) > 0) {
// append the conditions
$query .= " WHERE " . implode (' AND ', $conditions); // you can change to 'OR', but I suggest to apply the filters cumulative
}
$result = mysqli_query($mysqli_link, $query) or die(mysql_error());
mysqli_close($mysqli_link);
if(isset($_POST['submit'])) {
while($row = mysqli_fetch_assoc($result)) {
$C_Name = $row['C_Name'];
$C_StreetNumber = $row['C_StreetNumber'];
$C_StreetName = $row['C_StreetName'];
$C_Postcode = $row['C_Postcode'];
$C_County = $row['C_County'];
$C_Tele = $row['C_Tele'];
$C_Website = $row['C_Website'];
$Contact_Forename = $row['Contact_Forename'];
$Contact_Surname = $row['Contact_Surname'];
$Contact_Email = $row['Contact_Email'];
$Job_Type = $row['Job_Type'];
$Job_Price = $row['Job_Price'];
echo "<b>Name: $C_Name</b><br>Street Number: $C_StreetNumber<br>Street Name: $C_StreetName<br>Postcode: $C_Postcode<br>County: $C_County<br>Telephone: $C_Tele<br>Website: $C_Website<br>Contact Name: $Contact_Forename $Contact_Surname<br>Email: $Contact_Email<br>Job Type: $Job_Type<br>Job Price: $Job_Price<hr><br>";
}
}
}
?>
For some reason it is returning that there is "
unexpected end of file
" however I've checked the code and all the codes is closed off correctly (from what I can see) when I add another '}' in at the end the script doesn't return anything at all. Anyone know why this would be happening?
Source:
Search MySQL Database with Multiple Fields in a Form
Because you forget to close
if(isset($_POST['submit'])) {// you not close the condition
At the end of your file
Just add } at end of your file
Fixed:
if(isset($_POST['submit'])) {
// define the list of fields
$fields = array('C_Name', 'C_City', 'Job_Type', 'Review_Rate');
$conditions = array();
}
// builds the query
$query = "SELECT Company.C_Name, Company.C_StreetNumber, C_StreetName, C_Postcode, C_City, C_County, C_Tele, C_Website, Contact_Forename, Contact_Surname, Contact_Email, Job_Type, Job_Price, Review_Rate, Review_Comment
FROM Company
INNER JOIN Jobs ON Company.Company_ID = Jobs.Company_ID
INNER JOIN Review ON Jobs.Job_ID = Review.Job_ID";
// loop through the defined fields
foreach($fields as $field){
// if the field is set and not empty
if(isset($_POST[$field]) && !empty($_POST[$field])) {
// create a new condition while escaping the value inputed by the user (SQL Injection)
$conditions[] = "$field LIKE '%" . mysqli_real_escape_string($mysqli_link, $_POST[$field]) . "%'";
}
}
// if there are conditions defined
if(count($conditions) > 0) {
// append the conditions
$query .= " WHERE " . implode (' AND ', $conditions); // you can change to 'OR', but I suggest to apply the filters cumulative
}
echo "$query";
$result = mysqli_query($mysqli_link, $query);
mysqli_close($mysqli_link);
if(isset($_POST['submit'])) {
while($row = mysqli_fetch_array($result)) {
$C_Name = $row['C_Name'];
$C_StreetNumber = $row['C_StreetNumber'];
$C_StreetName = $row['C_StreetName'];
$C_Postcode = $row['C_Postcode'];
$C_City = $row['C_City'];
$C_County = $row['C_County'];
$C_Tele = $row['C_Tele'];
$C_Website = $row['C_Website'];
$Contact_Forename = $row['Contact_Forename'];
$Contact_Surname = $row['Contact_Surname'];
$Contact_Email = $row['Contact_Email'];
$Job_Type = $row['Job_Type'];
$Job_Price = $row['Job_Price'];
$Rating = $row['Review_Rate'];
$Comment = $row['Review_Comment'];
echo "<b>Name: $C_Name</b><br>Street Number: $C_StreetNumber<br>Street Name: $C_StreetName<br>City: $C_City<br>Postcode: $C_Postcode<br>County: $C_County<br>Telephone: $C_Tele<br>Website: $C_Website<br>Contact Name: $Contact_Forename $Contact_Surname<br>Email: $Contact_Email<br>Job Type: $Job_Type<br>Job Price: $Job_Price<br>Rating: $Rating<br>Comment: $Comment<hr><br>";
}
}
?>

Sum Values From Different Columns

I am having problem adding up the values in a column with php.
These values where sent from checkboxes and i want to count only the values that where checked from the unit column.
Here is my code:
<?php
$id = $_POST['course'];
foreach($id as $value)
{
//echo $value;
$query = " SELECT * FROM french WHERE id= $value ";
$result = mysql_query($query) or die('Error, query failed');
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$course = htmlspecialchars($row['course_name']);
$code = htmlspecialchars($row['course_code']);
$unit = $row['unit'];
$status = $row['status'];
?>
Are you trying like this? Getting form array of form checkboxs and checking on database via ID's?
HTML FORM
Check 1 <input type="checkbox" name="val[]" />
Check 2 <input type="checkbox" name="val[]" />
PHP RESULT
$val = $_POST['val'];
$count = count($val);
foreach ($val as $val_res)
{
$query = 'SELECT * FROM french WHERE id='.$val_res;
}

How can I make better design about understanding which checkbox is checked in order to put its value to mysql?

I have 2 checkboxes. Their values go to another php file and if any of them is checked, its value is inserted mysql codes. I did it, but when the number of checkbox increase and more advanced things appear, my code will be impossible to put into practise.
Here is checkbox.php :(it is inside a form)
<div>
<label>Choose:</label>
<label>Camera </label><input type="checkbox" name="kind[]" value="1" />
<label>Video </label><input type="checkbox" name="kind[]" value="2"/>
</div>
when the form is clicked, it goes to fetch_kind.php via AJAX and jquery($.post).
Here is code:
<?php
$kind = array();
$kind = $_POST['kind'];
$count = count($kind);
if ($count== 0) {
echo "You did not checked any of checkboxes!!!";
}
if ($count == 2) {
$sql = "SELECT id,kind FROM products";
} else {
foreach ($kind as $value) {
if ($value =="1") {
$sql = "SELECT id,kind FROM products WHERE kind = " . $value;
}
if ($value =="2") {
$sql = "SELECT id,kind FROM products WHERE kind = " . $value;
}
}
}
?>
Could you give a better example? Thank you...
A simple way would be to group all the values and us IN
if ($count > 0){
$sql = "SELECT id,kind FROM products WHERE kind IN (" . implode (',', $kind) . ")";
}
Also you might want to look into sanitizing you input.
You can loop through all your checkboxes and add a simple condition to an array. You implode the array at the end.
Something like:
$conds = array();
foreach ($kind as $value) {
$conds[] = '`kind` = ' . intval($value);
}
$sql = "SELECT id,kind FROM products WHERE " . implode(" OR ", $conds);

Categories