Am trying to use order by date and price low to high in this statement
SELECT * FROM allpostdata WHERE sts = '1' AND mca='Vehicle' ORDER BY pdt DESC, prs ASC
i used echo $query; to get the query and here is how i did,
looking for ORDER BY pdt DESC, is default query i want prs to be user option .
when i select order by low to high or high to low the statement changes but query does nothing, its not sorting by price
How do i sort by prs any solution?
pdt means Date and prs means Price
HTML
<div class="dropdown-menu dropdown-menu-right" aria-labelledby="sortby">
<li class="dropdown-item">
<div class="md-radio my-1">
<input type="radio" class="filter_all sort" name="sort" id="asc" value="ASC">
<label for="asc">Price : Low to High</label>
</div>
</li>
<li class="dropdown-item">
<div class="md-radio my-1">
<input type="radio" class="filter_all sort" name="sort" id="desc" value="DESC">
<label for="desc">Price : High to Low</label>
</div>
</li>
</div>
Script
$(document).ready(function () {
filter_data();
function filter_data() {
$.post(
"fetch.php",
{
action: 'fetch_data',
cate: get_filter('cate'),
brand: get_filter('brand'),
model: get_filter('model'),
sort: get_filter('sort'),
date: get_filter('date')
}
)
.done(function (data) {
$('.filter_data').html(data);
});
}
function get_filter(class_name) {
var filter = [];
$('.' + class_name + ':checked').each(function () {
filter.push($(this).val());
});
return filter;
}
$('.filter_all').click(function () {
filter_data();
});
});
PHP
if (isset($_POST["action"])) {
$query = "SELECT * FROM allpostdata WHERE sts = '1' AND mca='Vehicle'";
if (!empty($_POST['cate'])) {
$query .= " AND sca IN (" . str_repeat("?,", count($_POST['cate']) - 1) . "?)";
} else {
$_POST['cate'] = []; // in case it is not set
}
if (!empty($_POST['brand'])) {
$query .= " AND product_brand IN (" . str_repeat("?,", count($_POST['brand']) - 1) . "?)";
} else {
$_POST['brand'] = []; // in case it is not set
}
if (!empty($_POST['model'])) {
$query .= " AND mdl IN (" . str_repeat("?,", count($_POST['model']) - 1) . "?)";
} else {
$_POST['model'] = []; // in case it is not set
}
$query .= " ORDER BY pdt DESC";
if (!empty($_POST['sort'])) {
if ($_POST["sort"][0] == "ASC" || $_POST["sort"][0] == "DESC") { //simplistic whitelist
$query .= ", prs " . $_POST['sort'][0];
}
}
echo $query;
$stmt = $conn->prepare($query);
$params = array_merge($_POST['cate'], $_POST['brand'], $_POST['model']);
$stmt->execute($params);
$result = $stmt->fetchAll();
$total_row = $stmt->rowCount();
$output = '';
Add a third button for "Sort by date".
<div class="dropdown-menu dropdown-menu-right" aria-labelledby="sortby">
<li class="dropdown-item">
<div class="md-radio my-1">
<input type="radio" class="filter_all sort" name="sort" id="asc" value="ASC">
<label for="asc">Price : Low to High</label>
</div>
</li>
<li class="dropdown-item">
<div class="md-radio my-1">
<input type="radio" class="filter_all sort" name="sort" id="desc" value="DESC">
<label for="desc">Price : High to Low</label>
</div>
</li>
<li class="dropdown-item">
<div class="md-radio my-1">
<input type="radio" class="filter_all sort" name="sort" id="date" value="date">
<label for="date">Date : High to Low</label>
</div>
</li>
</div>
if (empty($_POST['sort']) || $_POST['sort'][0] == "date") {
$query .= " ORDER BY pdt DESC";
} elseif ($_POST["sort"][0] == "ASC" || $_POST["sort"][0] == "DESC") {
$query .= " ORDER BY prs " . $_POST['sort'][0];
}
Related
I want to use JS library "Semantic-UI" with my PHP code
I want to replace the ordinary select boxes with "Semantic-UI Multiple selection Dropdown"
The original PHP Code that generates the Select items:
<div class="list-group">
<h3>Material</h3>
<?php
$query = "SELECT DISTINCT(product_gender) FROM product";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
foreach($result as $row)
{
?>
<div class="list-group-item checkbox">
<label><input type="checkbox" class="common_selector gender" value="<?php echo $row['product_gender']; ?>" > <?php echo $row['product_gender']; ?></label>
</div>
<?php
}
?>
</div>
I want to replace input with Semantic-UI :
<div class="list-group">
<h3>Gender</h3>
<select multiple="" class="label ui selection fluid dropdown">
<?php
$query = "SELECT DISTINCT(product_gender) FROM product";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
foreach($result as $row)
{
?>
<div class="list-group-item checkbox">
<option name='gender' class="common_selector gender" value="<?php echo $row['product_gender']; ?>"><?php echo $row['product_gender']; ?></option>
</div>
<?php
}
?>
</select>
</div>
It gathers the options, But didn't post data, since the function that posts data is :
<script>
$(document).ready(function(){
filter_data();
function filter_data()
{
$('.filter_data').html('<div id="loading" style="" ></div>');
var action = 'fetch_data';
var es2 = get_filter('es2');
var bw2 = get_filter('bw2');
var tl = get_filter('tl');
var b2 = get_filter('b2');
var gender = get_filter('gender');
var material = get_filter('material');
var hinge = get_filter('hinge');
$.ajax({
url:"fetch_data.php",
method:"POST",
data:{action:action, es2:es2, bw2:bw2, tl:tl, b2:b2, gender:gender, material:material, hinge:hinge},
success:function(data){
$('.filter_data').html(data);
}
});
}
function get_filter(class_name)
{
var filter = [];
$('.'+class_name+':checked').each(function(){
filter.push($(this).val());
});
return filter;
}
$('.common_selector').click(function(){
filter_data();
});
});
And we get Data by this :
if(isset($_POST["gender"]))
{
$gender_filter = implode("','", $_POST["gender"]);
$query .= "
AND product_gender IN('".$gender_filter."')
";
}
if(isset($_POST["material"]))
{
So please how can I merge Semantic-UI with my code ?
I have problem with this product filter. Problem could be with implode() or with IN ('{$platforma_filter}')
Every time it outputs only my echo No Data Found, but when I delete this:
if(isset($_POST["platforma"]))
{
$platforma_filter = implode(',', $_POST["platforma"]);
$query .= "
AND id_platformy IN ('{$platforma_filter}')
";
}
if(isset($_POST["typ"]))
{
$typ_filter = implode(',', $_POST["typ"]);
$query .= "
AND id_typu IN('{$typ_filter}')
";
}
if(isset($_POST["zanr"]))
{
$zanr_filter = implode(',', $_POST["zanr"]);
$query .= "
AND id_zanr IN('{$zanr_filter}')
";
}
Then output is all products.
if(isset($_POST["action"]))
{
$query = "
SELECT * FROM produkty WHERE
";
/*if(isset($_POST["minimum_price"], $_POST["maximum_price"]) && !empty($_POST["minimum_price"]) && !empty($_POST["maximum_price"]))
{
$query .= "
AND cena BETWEEN '".$_POST["minimum_price"]."' AND '".$_POST["maximum_price"]."'
";
} */
if(isset($_POST["platforma"]))
{
$platforma_filter = implode(',', $_POST["platforma"]);
$query .= "
AND id_platformy IN ('{$platforma_filter}')
";
}
if(isset($_POST["typ"]))
{
$typ_filter = implode(',', $_POST["typ"]);
$query .= "
AND id_typu IN('{$typ_filter}')
";
}
if(isset($_POST["zanr"]))
{
$zanr_filter = implode(',', $_POST["zanr"]);
$query .= "
AND id_zanr IN('{$zanr_filter}')
";
}
<?php
$query = "SELECT DISTINCT(nazev_platformy),id_platformy FROM Platformy ORDER BY nazev_platformy DESC";
$statement = $conn->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
foreach($result as $row)
{
?>
<div class="list-group-item checkbox">
<label><input type="checkbox" class="common_selector brand" value="<?php echo $row['id_platformy']; ?>" > <?php echo $row['nazev_platformy']; ?></label>
</div>
<?php
}
?>
</div>
</div>
<div class="list-group">
<h3>Typ Produktu</h3>
<?php
$query = "
SELECT DISTINCT(nazev_typu),id_typu FROM typ_produktu ORDER BY nazev_typu DESC
";
$statement = $conn->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
foreach($result as $row)
{
?>
<div class="list-group-item checkbox">
<label><input type="checkbox" class="common_selector ram" value="<?php echo $row['id_typu']; ?>" > <?php echo $row['nazev_typu']; ?></label>
</div>
<?php
}
?>
</div>
<div class="list-group">
<h3>Žánr hry</h3>
<?php
$query = "
SELECT DISTINCT(nazev),id_zanr FROM zanr ORDER BY nazev DESC
";
$statement = $conn->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
foreach($result as $row)
{
?>
<div class="list-group-item checkbox">
<label><input type="checkbox" class="common_selector storage" value="<?php echo $row['id_zanr']; ?>" > <?php echo $row['nazev']; ?></label>
</div>
<?php
}
?>
</div>
</div>
<div class="col-md-9">
<br />
<div class="row filter_data">
</div>
</div>
</div>
</div>
<script>
$(document).ready(function(){
filter_data();
function filter_data()
{
$('.filter_data').html('<div id="loading" style="" ></div>');
var action = 'fetch_data';
var minimum_price = $('#hidden_minimum_price').val();
var maximum_price = $('#hidden_maximum_price').val();
var platforma = get_filter('platforma');
var typ = get_filter('typ');
var zanr = get_filter('zanr');
$.ajax({
url:"fetch_data.php",
method:"POST",
data:{action:action, minimum_price:minimum_price, maximum_price:maximum_price, platforma:platforma, typ:typ, zanr:zanr},
success:function(data){
$('.filter_data').html(data);
}
});
}
function get_filter(class_name)
{
var filter = [];
$('.'+class_name+':checked').each(function(){
filter.push($(this).val());
});
return filter;
}
$('.common_selector').click(function(){
filter_data();
});
$('#price_range').slider({
range:true,
min:0,
max:65000,
values:[0, 65000],
step:50,
stop:function(event, ui)
{
$('#price_show').html(ui.values[0] + ' - ' + ui.values[1]);
$('#hidden_minimum_price').val(ui.values[0]);
$('#hidden_maximum_price').val(ui.values[1]);
filter_data();
}
});
});
</script>
I am created form to select value to display in my page table.Below is my code to select multiple values and search to display, but it is not displaying the selected values (type and dates) in multiple dropdownlist. Anyone can help me solve this problem? Thanks.
My frontend coding:
<div class="box inverse">
<div class="row">
<div class="col-lg-12">
<header>
<h5>Search</h5>
</header>
<form id="transaction_search">
<div class="form-group">
<div class="col-lg-12">
<div class="col-lg-3">
</div>
<div class="col-lg-12">
<div class="form-group">
<div class="col-lg-12">
<label for="text1" class="form-group control-label col-lg-2"><?php echo $language['type']; ?>:</label>
<div class="col-lg-5">
<select id="select_type" class="form-group form-control required"">
<option value="transfer" selected><?php echo $language["transfer"]; ?></option>
<option value="withdraw"><?php echo $language["withdraw"]; ?></option>
<option value="upgrade"><?php echo $language["upgrade"]; ?></option>
<option value="register"><?php echo $language["register"]; ?></option>
<option value="receive"><?php echo $language["receive"]; ?></option>
</select>
</div>
</div>
</div>
<div class="col-lg-12 form-group">
<label for="text1" class="form-group control-label col-lg-2">Date Range:</label>
<div class="col-lg-2">
<?php echo custom_period_opt(); ?>
</div>
<label for="text1" class="form-group control-label col-lg-2">Date Created:</label>
<div class="col-lg-2">
<input type="text" class="form-group form-control datepicker" id="start_date" name="start_date" data-date-format="dd-mm-yyyy" title="" value="<?php echo $new_cur_date; ?>" readonly>
</div>
<label for="text1" class="form-group control-label col-lg-2">To</label>
<div class="col-lg-2">
<input type="text" class="form-group form-control datepicker" id="end_date" name="end_date" data-date-format="dd-mm-yyyy" title="" value="<?php echo $new_cur_date; ?>" readonly>
</div>
</div>
</div>
</div>
</div>
<div class="col-lg-12" style="text-align:center; padding-bottom:10px; padding-top:10px;">
<button id="search" type="button" class="btn btn-sm btn-primary" onclick="search_('transaction_search','transaction_result','transaction_table')">Search</button>
<button id="clear" type="button" class="btn btn-sm btn-default" onclick="clearData()">Clear</button>
</div>
<div class="body" id="transaction_result" style="overflow:auto;">
</div><!--body-->
</form>
</div>
</div>
My backend coding (This is part of coding I try to select "Withdraw" option to test output, but did't display any data in the table. This coding is want to select "withdraw" and select what I choose the "date"):
<?php
foreach ($_POST as $key => $value) {
$_POST[$key] = trim(preg_replace('/\s+/', ' ', ($value)));
}
$arr_val = $_POST;
$loc = $arr_val['loc'];
$action = $arr_val['action'];
$select_type = $_POST['select_type'];
unset($arr_val['loc']);
unset($arr_val['action']);
unset($arr_val['select_type']);
$tbl_name = 'withdrawal_record';
if ($action == 'search' && $select_type == 'withdraw' ) {
if ($_POST['select_type'] != '' || $_POST['start_date'] != '' || $_POST['end_date'] != '' ) {
$sql = 'SELECT * FROM ' . $tbl_name . ' WHERE id is not null';
if($_POST['start_date']!='' && $_POST['end_date']!= '') {
$sql .=' and a.created between "' . date('Y-m-d', strtotime($_POST['start_date'])) . '" and "' . date('Y-m-d', strtotime($_POST['end_date'])) . '"';
}
$result_arr['sql'] = $sql;
$result_arr = get_data_list($sql);
$i = 1;
echo '<table id="dataTable_1" class="dataTable table table-bordered table-condensed table-hover table-striped" style="padding:0px;" border="1">
<thead>
<tr>
<th>No</th>
<th>Date</th>
<th>Amount</th>
</tr>
</thead>
<tbody>';
foreach ($result_arr as $rs_search) {
echo "<tr>";
echo "<td>" . $i++ . "</td>";
echo "<td>" . $rs_search['created'] . "</td>";
echo "<td>" . $rs_search['withdraw_amount'] . "</td>";
echo '</td>';
echo "</tr>";
}
echo '</tbody>';
echo '</table>';
}
}
?>
Below is jquery function:
function search_(form_id, div_id, act_file) {
var action = 'search';
var extra = '&action=' + action;
var serialized = $('#' + form_id).serialize();
var form_data = serialized + extra;
$.ajax({
//dataType: 'json',
type: 'POST',
url: '?f=' + act_file,
data: form_data,
beforeSend: function() {
show_overLay();
$('#' + div_id).html('');
},
success: function(data) {
hide_overLay('');
if (data) {
$("#" + div_id).append(data);
$('.dataTable').dataTable({
pageLength: 25,
destroy: true
});
} else {
hide_overLay("Please fill in the field.");
}
//console.log(data);
}
});
}
Below is my "withdrawal_record" table:
withdrawal_record
Below is my output, and didn't show the data what I select. Actually I want to select date between 04/11/19 and 07/11/19 and select type is "Withdraw" :
Output 1
If success , that will show like below the output picture:
Output 2
Error output:
Output 3
In html add multiple attribute to select :
<select id="select_type" class="form-group form-control required" multiple>
In JQuery make these changes:
Remove these :
var action = 'search';
var extra = '&action=' + action;
var serialized = $('#' + form_id).serialize();
var form_data = serialized + extra;
And in Ajax request:
Remove these lines:
data: form_data,
Add these lines:
data:{action:"search","loc":$("#select_type").val().toString()},
In PHP remove these lines :
foreach ($_POST as $key => $value) {
$_POST[$key] = trim(preg_replace('/\s+/', ' ', ($value)));
}
$arr_val = $_POST;
$loc = $arr_val['loc'];
$action = $arr_val['action'];
And these lines instead:
$loc = $_POST['loc'];
$action = $_POST['action'];
$loc =explode(","$loc );
foreach($loc AS $val)
{
echo $val; // your locations
}
I have 3 column in my database as bodybuild, ethnictype and skincolor in table accounts. I need to search all the three columns at a time to fetch values from it using check boxes.
<h4 style="margin-left: 10px; color: gray;">Body Build Types</h4><ol><input type="checkbox" name="bodybuild[]" value="1" />Six Pack<br><input type="checkbox" name="bodybuild[]" value="2" />Fat<br><input type="checkbox" name="bodybuild[]" value="3" />Thin<br></ol><h4 style="margin-left: 10px; color: gray;">Ethnic Types</h4><ol><input type="checkbox" name="ethnictype[]" value="4" />Arab<br><input type="checkbox" name="ethnictype[]" value="5" />Indian<br></ol><h4 style="margin-left: 10px; color: gray;">Skin Color Types</h4><ol><input type="checkbox" name="skincolor[]" value="6" />Black<br><input type="checkbox" name="skincolor[]" value="7" />White<br></ol><input style="margin-left: 10px" type="submit" value='Search' /><br><br><input type="hidden" name="tab1" value="search"></form>
Column bodybuild contain 3 values as 1, 2 and 3
Column ethnictype contain 2 values as 4 and 5
Colum skincolor contain 2 values as 6 and 7
I want to pass the values selcted in check boxes from view page into url like this
/search/1&2&3&4&5&6&7 - when selecting all check boxes and
/search/1&4&6 - when selecting three values (1,4,6) or any other ways.
I can fetch single values from table (as /search/1) but not multiple values.
Please help. Thank you!!!
At last with the help of AJAX I got the solutions to my question. Thanks to all of them who had supported me. Iam posting the code for further candidates.
index.php
<body>
<h1>Demo</h1>
<table id="employees"><thead>
<tr><th>Name</th>
<th>BodyBuild</th>
<th>EthnicType</th>
<th>Skincolor</th></tr>
</thead><tbody></tbody>
</table>
<div id="filter">
<h2>Filter options</h2>
<div>
<h4>Body Build</h4>
<input type="checkbox" id="car" name="sixpack">
<label for="car">Six Pack</label>
</div>
<div>
<input type="checkbox" id="car" name="fat">
<label for="car">Fat</label>
</div>
<div>
<input type="checkbox" id="car" name="thin">
<label for="car">Thin</label>
</div>
<div>
<h4>Ethnic Type</h4>
<input type="checkbox" id="language" name="arab">
<label for="language">Arab</label>
</div>
<div>
<input type="checkbox" id="language" name="indian">
<label for="language">Indian</label>
</div>
<div>
<h4>Skin Color</h4>
<input type="checkbox" id="nights" name="black">
<label for="nights">Black</label>
</div>
<div>
<input type="checkbox" id="nights" name="white">
<label for="nights">White</label>
</div>
</div>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
function makeTable(data){
var tbl_body = "";
$.each(data, function() {
var tbl_row = "";
$.each(this, function(k , v) {
tbl_row += "<td>"+v+"</td>";
})
tbl_body += "<tr>"+tbl_row+"</tr>";
})
return tbl_body;
}
function getEmployeeFilterOptions(){
var opts = [];
$checkboxes.each(function(){
if(this.checked){
opts.push(this.name);
}
});
return opts;
}
function updateEmployees(opts){
$.ajax({
type: "POST",
url: "search",
dataType : 'json',
cache: false,
data: {filterOpts: opts},
success: function(records){
$('#employees tbody').html(makeTable(records));
}
});
}
var $checkboxes = $("input:checkbox");
$checkboxes.on("change", function(){
var opts = getEmployeeFilterOptions();
updateEmployees(opts);
});
updateEmployees();
</script>
</body>
search.php
<?php
$pdo = new PDO('mysql:host=localhost;dbname=castingkall', 'root', '');
$select = 'SELECT name,bodybuild,ethnictype,skincolor';
$from = ' FROM accounts';
$where = ' WHERE TRUE';
$opts = isset($_POST['filterOpts'])? $_POST['filterOpts'] : array('');
if (in_array("sixpack", $opts)){
$where .= " AND bodybuild = 1";
}
if (in_array("fat", $opts)){
$where .= " AND bodybuild = 2";
}
if (in_array("thin", $opts)){
$where .= " AND bodybuild = 3";
}
if (in_array("arab", $opts)){
$where .= " AND ethnictype = 4";
}
if (in_array("indian", $opts)){
$where .= " AND ethnictype = 5";
}
if (in_array("black", $opts)){
$where .= " AND skincolor = 6";
}
if (in_array("white", $opts)){
$where .= " AND skincolor = 7";
}
$sql = $select . $from . $where;
$statement = $pdo->prepare($sql);
$statement->execute();
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($results);
echo($json);
?>
Just change the database name, table name, column name and values according to your data.
Hope you find this useful
i'm trying to insert data to MySQL from a dynamic form with jQuery. For the record, I'm using Twitter Bootstrap. I actually achieved insert "rows" but with no data. The best help I found right now is this here for the insert to MySQL and here to jQuery script.
Thanks in advance for taking time for this.
File: add.php
<form action="../reglas/insert.php" method="post" class="form-horizontal">
<div class="container">
<div id="content">
<div class="row">
<a class="add_line btn btn-small" href="#" style="margin-left:5px">+</a>
</div>
<br>
</div>
</div>
</div>
</div>
<div style="margin:20px auto; width:80px;">
<input class="btn btn-success" type="submit" value="Guardar">
</div>
</form>
<script>
$("#content").delegate(".add_line", "click", function() {
var content = '<div class="row">' +
'<div class="span3"><div class="input-append"><input type="text" class="span2 text-right" placeholder="0.00" id="enganche" name="enganche" value="" /><span class="add-on">%</span></div></div>' +
'<div class="span3"><div class="input-append"><input type="text" class="span2 text-right" placeholder="0.00" id="comision" name="comision" value="" /><span class="add-on">%</span></div></div>' +
'<div class="span3"><div class="input-append"><input type="text" class="span2 text-right" placeholder="0.00" id="r1" name="r1[]" value="" /><span class="add-on">%</span></div></div>' +
'<div class="span2"><div class="input-append"><input type="text" class="span1 text-right" placeholder="0.00" id="r2" name="r2[]" value="" /><span class="add-on">%</span></div></div>'+
'<a class="del_line btn btn-small" href="#" style="margin-left:5px">-</a> ' +
'<br><br>'+
'</div>';
$("#content").append(content);
return false;
});
$("#content").delegate(".del_line", "click", function() {
$(this).parent().remove();
return false;
});
</script>
File: insert.php
The Connection:
$con=mysqli_connect("$host","$username","$password","$db_name");
mysqli_autocommit($con, false);
$flag=true;
The query:
$query="
INSERT INTO $tbl_name(
the_input,
)
VALUES (
'$the_input',
)";
The "for":
for ($i = 0; $i < count($_POST['the_input']); $i++) {
$the_input = $_POST['the_input'][$i];
$result = mysqli_query($con, $query);
if (!$result) {
$flag = false;
echo "Error details: " . mysqli_error($con). ". ";
}
}
if ($flag) {
mysqli_commit($con);
echo "Done!";
}
mysqli_close($con);
?>
Okey dokey.
First things first:
$.delegate() is deprecated so unless you are using a version that is < jQuery 1.7 (which is many versions ago) you should migrate to $.on() event binder/delegator function. This will ensure that your code is future proof (at least until they change the api again!)
Secondly:
I am assuming you have wrapped your data in a form tag and the values are actually getting send to the recieving page here is how I would do it:
if(isset($_POST['the_input']))
{
//create connection object;
$mysqli = new mysqli($host,$username,$password,$db_name);
$query = "INSERT INTO `the_input` VALUES (";
//construct the query. Get the the_input data and paramater string (required for stmt binding)
foreach($_POST['the_input'] as $value)
{
$query .= $value . ",";
}
//remove trailing comma
$query = substr($query, 0, strlen($query)-1);
$query .= ")";
//this is just so you can see what the loop did and test the output of the query, remove this when you're confident
echo "The constructed query string is: " . $query
if($mysqli->query($query) == false)
{
trigger_error($mysqli->error);
} else {
echo "Success! Check the DB!";
}
} else {
Echo "No POST data was recieved";
}