SQL query for data filtering - php

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{
}

Related

Data with Spaces in Database Are not fully Showing in Textbox

<input type="text" name="question" required class="form-control" placeholder="Question" value=<?php
$emid = $_GET['key1'];
$sql = "SELECT * FROM posses_ques WHERE id = '$emid'";
$result = mysqli_query($connection, $sql);
if (mysqli_num_rows($result) > 0){
while ($row = mysqli_fetch_assoc($result)) {
echo $row['ques'];
}
} else {
echo "No Data Available";
}
?>
>
A tidier solution and one that does not allow SQL Injection Attack might be something like this
<?php
$sql = "SELECT * FROM posses_ques WHERE id = ?";
$stmt = $connection->prepare($sql);
$stmt->bind_param('i', $_GET['key1']):
$stmt->execute();
$result = $stmt->get_result();
$x = 0;
if ( $result->num_rows > 0 ){
while ($row = $result->fetch_assoc()) {
echo '<input type="text" name="question' . $x . '" value="' . $row['ques']. ' required class="form-control" placeholder="Question" ';
$x++;
}
} else {
echo "No Data Available";
}
Note also the unique name attribute. These need to be unique or you wont see all of them in the data returned to the scripts from a form

How do get good result with multiple str_split text characters lines

In my php code below am trying to fetch a multiple text character from database and str_split each result output. add USED to the end line of each output and output remaining characters also i have tried:
require("init.php");
echo "<form action='reg.php' method='post'>
<b>booking code:</b><br />
<input type='text' name='book' size='17' />
<input type='submit' name='login' maxlength='2' size='2' value='PRINT OUT' />
</form>";
if(isset($_POST["login"]))
{
$book = mysqli_real_escape_string($conn, $_POST["book"]);
$sql = "SELECT `item_name` , `quantity` FROM `books` WHERE `book`='$book'"; $query = mysqli_query($conn, $sql);
while ($row1 = mysqli_fetch_array($query)) {
$d[] = $row1["item_name"];
$v[] = $row1["quantity"];
foreach($d as $r);
foreach($v as $ro);
$get = array(0 => array("yes" => $r, "no" => $ro));
foreach ($get as $item) {
$getd = $item["yes"];
}
$sql = mysqli_query($conn, "SELECT * FROM promo WHERE code='$getd' LIMIT 1");
while ($row = mysqli_fetch_array($sql)) {
$type = $row["name"];
$code = $row["recharge"];
$deta = $row["details"];
$logo = $row["logo"];
$price = $row["price"];
if(preg_match('/(xyz)/i', $type)) $type = "20";
if(preg_match('/(log)/i', $type)) $type = "16";
}
$id = $item["no"];
$result = str_split($code, $type);
$a = "";
$c = "";
for($b = 0; $b<$id; $b++)
{
$a .= $result[$b];
}
$b = "USED";
for($bn = $id; $bn<sizeof($result); $bn++){
$c .= $result[$bn];
}
echo $a.$b.$c;
}
}
}
and all my result output with code is unknow am saying all result all complecated result output thanks for your time and impact in my solutions

Vote up-down using Mysql , Jquery and Php

I am trying to make vote up-down system using php ,mysql and jquery. It works perfectly on front-end but, at the back-end it does not add data in the database. Any help/suggestions will be appreciated..!! Following is the code..
<span id="links-<?php echo $rec1['que_id']; ?>">
<input type="hidden" id="votes-<?php echo $rec1['que_id']; ?>" value="<?php echo $rec1['votes']; ?>">
<?php
$vote_rank = 0;
$query ="SELECT SUM(vote_rank) as vote_rank FROM cvotes WHERE que_id = '".$rec1['que_id']."' and username = '$logged_user'";
$result2 = $conn->query($query);
foreach ($result2 as $roww) {
$up = "";
$down = "";
if(!empty($roww["vote_rank"])) {
$vote_rank = $roww["vote_rank"];
if($vote_rank == -1) {
$up = "enabled";
$down = "disabled";
}
if($vote_rank == 1) {
$up = "disabled";
$down = "enabled";
}
}
?>
<input type="hidden" id="vote_rank_status-<?php echo $rec1['que_id']; ?>" value="<?php echo $vote_rank; ?>">
<span class="btn-votes">
<input type="button" title="Up" class="up" onClick="addVote(<?php echo $rec1['que_id']; ?>,'1')" <?php echo $up; ?> />
<span class="label-votes"><?php echo $rec1['votes']; ?></span>
<input type="button" title="Down" class="down" onClick="addVote(<?php echo $rec1['que_id']; ?>,'-1')" <?php echo $down; ?> />
<p id='show'></p>
</span>
function addVote(que_id,vote_rank) {
$.ajax({
data:'que_id='+que_id+'&vote_rank='+vote_rank,
url: "add_vote.php",
type: "POST",
beforeSend: function(){
$('#links-'+que_id+' .btn-votes').html("<img src='LoaderIcon.gif' />");
},
success: function(vote_rank_status){
var votes = parseInt($('#votes-'+que_id).val());
var vote_rank_status;// = parseInt($('#vote_rank_status-'+que_id).val());
switch(vote_rank) {
case "1":
votes = votes+1;
vote_rank_status = vote_rank_status+1;
break;
case "-1":
votes = votes-1;
vote_rank_status = vote_rank_status-1;
break;
}
$('#votes-'+que_id).val(votes);
$('#vote_rank_status-'+que_id).val(vote_rank_status);
var up,down;
if(vote_rank_status == 1) {
up="disabled";
down="enabled";
}
if(vote_rank_status == -1) {
up="enabled";
down="disabled";
}
var vote_button_html = '<input type="button" title="Up" class="up" onClick="addVote('+que_id+',\'1\')" '+up+' /><span class="label-votes">'+votes+'</span><input type="button" title="Down" class="down" onClick="addVote('+que_id+',\'-1\')" '+down+' />';
$('#links-'+que_id+' .btn-votes').html(vote_button_html);
}
});
}
<?php
//-----add_vote.php-----
if(!empty($que_id)) {
if(isset($_SESSION['login_user']))
{
$logged_user = $_SESSION['login_user'];
}
$que_id=$_POST["que_id"];
$vote_rank = $_POST["vote_rank"];
require_once("dbcontroller.php");
$db_handle = new DBController();
$query = "INSERT INTO cvotes (que_id,username,vote_rank) VALUES ('$que_id','$logged_user','$vote_rank')";
$result = $db_handle->insertQuery($query);
if(!empty($result)) {
$query = "SELECT SUM(vote_rank) as vote_rank FROM cvotes WHERE que_id = '$que_id' and username = '$logged_user'";
$row = $db_handle->runQuery($query);
switch($vote_rank) {
case "1":
$update_query ="UPDATE questions SET votes = votes+1 WHERE que_id='" . $que_id . "'";
break;
case "-1":
$update_query ="UPDATE questions SET votes = votes-1 WHERE que_id='" . $que_id . "'";
break;
}
$result = $db_handle->updateQuery($update_query);
print $roww["vote_rank"];
}
}
?>
Seems to that your insert query is wrong "INSERT INTO cvotes (que_id,username,vote_rank) VALUES ('$que_id','$logged_user','$vote_rank')", try to use the quotes according to the data type.. you have gave quotes for all the values, i think except username rest are integer datatypes then change the query as
"INSERT INTO cvotes (que_id,username,vote_rank) VALUES ($que_id,"'"+$logged_user+"'",$vote_rank)";
Okay,so finally issue solved..!! Had just minor errors of variables and linking..below is the code..
Added hidden input :
">
Some changes in add_vote.php :
<?php
include('../connection.php');
session_start();
if(isset($_SESSION['login_user']))
{
$logged_u = $_SESSION['login_user'];
}
if(!empty($_POST["que_id"])) {
require_once("dbcontroller.php");
$db_handle = new DBController();
$query = "INSERT INTO cvotes (username,que_id,vote_rank) VALUES ('".$logged_u."','" . $_POST["que_id"] . "','" . $_POST["vote_rank"] . "')";
$result = $db_handle->insertQuery($query);
if(!empty($result)) {
$query = "SELECT SUM(vote_rank) as vote_rank FROM cvotes WHERE que_id = '" . $_POST["que_id"] . "' and username = '".$logged_u."' ";
$row = $db_handle->runQuery($query);
switch($_POST["vote_rank"]) {
case "1":
$update_query ="UPDATE questions SET votes = votes+1 WHERE que_id='" . $_POST["que_id"] . "'";
break;
case "-1":
$update_query ="UPDATE questions SET votes = votes-1 WHERE que_id='" . $_POST["que_id"] . "'";
break;
}
$result = $db_handle->updateQuery($update_query);
print $roww["vote_rank"];
}
}
?>

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);
?>

Forming a query string from multiple checkboxes

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;

Categories