Mysql Table Sorting in Php (Client side) - javascript

Can any one help how to sort the database results in php
i have pasted the my code below. it display the result but sorting cannot be done.
Any help in this regard
<script language="JavaScript" type="text/javascript">
<!--
var sortedOn = 0;
function SortTable(sortOn) {
var table = document.getElementById('results');
var tbody = table.getElementsByTagName('tbody')[0];
var rows = tbody.getElementsByTagName('tr');
var rowArray = new Array();
for (var i=0, length=rows.length; i<length; i++) {
rowArray[i] = rows[i].cloneNode(true);
}
if (sortOn == sortedOn) { rowArray.reverse(); }
else {
sortedOn = sortOn;
if (sortedOn == 0) {
rowArray.sort(RowCompareNumbers);
}
else if (sortedOn == 3) {
rowArray.sort(RowCompareDollars);
}
else {
rowArray.sort(RowCompare);
}
}
var newTbody = document.createElement('tbody');
for (var i=0, length=rowArray.length; i<length; i++) {
newTbody.appendChild(rowArray[i]);
}
table.replaceChild(newTbody, tbody);
}
function RowCompare(a, b) {
var aVal = a.getElementsByTagName('td')[sortedOn].firstChild.nodeValue;
var bVal = b.getElementsByTagName('td')[sortedOn].firstChild.nodeValue;
return (aVal == bVal ? 0 : (aVal > bVal ? 1 : -1));
}
function RowCompareNumbers(a, b) {
var aVal = parseInt(a.getElementsByTagName('td')
[sortedOn].firstChild.nodeValue);
var bVal = parseInt(b.getElementsByTagName('td')
[sortedOn].firstChild.nodeValue);
return (aVal - bVal);
}
function RowCompareDollars(a, b) {
var aVal = parseFloat(a.getElementsByTagName('td')
[sortedOn].firstChild.nodeValue.substr(1));
var bVal = parseFloat(b.getElementsByTagName('td')
[sortedOn].firstChild.nodeValue.substr(1));
return (aVal - bVal);
}
//-->
</script>
Php MySql Query
<?php
$job_id = $_GET['id'] ;
$sql="SELECT date, fullname, city, education from table_name
WHERE id = 'job_id'";
$result=mysql_query($sql); ?>
<table id="results" style="width:980px;">
<thead>
<tr>
<th style="width:60px;"><a onclick="SortTable(0);" href="javascript:;">Date</a></th>
<th style="width:150px;"><a onclick="SortTable(1);" href="javascript:;">Name</a></th>
<th style="width:70px;"><a onclick="SortTable(2);" href="javascript:;">City</a></th>
<th style="width:70px;"><a onclick="SortTable(3);"href="javascript:;">Education</a>
</th>
<?php while($rows=mysql_fetch_array($result)){
?>
<tbody>
<tr>
<td>1</td>
<td><? echo $fullname ; ?></td>
<td><? echo $city ; ?></td>
<td><? echo $b_education ; ?></td>
</tr>
</tbody>
<?
}
?>
</table>

$job_id = $_GET['id'] ;
$sql="SELECT date, fullname, city, education from table_name
WHERE id = 'job_id'";
will not work,
first it should id = '" . $job_id . "' (your WHERE condition search for the id "job_id" not the $job_id variable
2nd based on this lines, google the words "sql injection" ... thats a big security issue! (msyql_real_escape for example)
3rd, mysql provides ORDER functions... if you want client side order, build the result, convert it to json (json_encode) and handle it with javascript, but yours is crappy ^^
regards
Thomas

Related

How to trigger onChange event when form is submitted?

I'm trying to populate HTML table with filter(two dropdowns) from CSV file by using PHP, JS, and jQuery. When user open the page user will see below dropdown,
the options for this drop downs are file names in the dir.
<form name="form1" method="post">
<select class="form-control col-sm-5" onChange="document.forms['form1'].submit();" id="choosefile" name="choosefile">
<option value="" selected>Choose Term</option>
<?php
foreach ($files as &$value) {
echo '<option value="' . $value . '">' . $value . '</option>';
}
?>
</select>
</form>
when user submit the form below PHP code gets executed
<?php
if(isset($_POST['choosefile']) && !empty($_POST['choosefile'])) {
$t = $_POST["choosefile"];
$filepath = "uploads/$t";
$row = 0;
$the_big_array = [];
$unique_start_date = [];
$unique_ids = array();
if (($h = fopen("{$filepath}", "r")) !== false) {
while (($data = fgetcsv($h, 1000, ",")) !== false) {
$the_big_array[] = $data;
$unique_ids[] = $data[0];
$a unique_start_date[] = $data[1];
}
fclose($h);
}
//closing bracket for parent if statement is at the end of the file
?>
Below two dropdowns act as a filter
<select name="" id="session_id">
<option value="">[Select Session]</option>
</select>
<select name="" id="start_date">
<option value="">[Select Start Date]</option>
</select>
<table border="1" class="table" id="personDataTable">
<thead>
<tr>
<th scope="col">Session</th>
<th scope="col">Start Date</th>
</tr>
</thead>
<tbody id='tbody'>
</tbody>
</table>
<script>
var obj1 = <?php array_shift($the_big_array); echo json_encode($the_big_array); ?>;
var obj2 = <?php array_shift($unique_start_date); echo json_encode(array_unique($unique_start_date)); ?>;
var obj3 = <?php array_shift($unique_ids); echo json_encode(array_unique($unique_ids)); ?>;
var table = document.getElementById("personDataTable").getElementsByTagName("tbody")[0];
var temp,temp1 = {};
var row = 0;
$("#choosefile, #session_id, #start_date").on('change', function() {
var d1 = $( "#session_id" ).val();
var d2 = $( "#start_date" ).val();
$("#tbody").empty();
for (var i = 0; i < obj1.length; i++) {
if (d1 && obj1[i][0] !== d1 && row > -1) continue;
if (d2 && obj1[i][1] !== d2 && row > -1) continue;
row++;
newTr.insertCell(-1).appendChild(document.createTextNode(obj1[i][0]));
newTr.insertCell(-1).appendChild(document.createTextNode(obj1[i][1]));
}
});
</script>
<?php }?>
The problem I'm having is when user submit first dropdown(options with file name) table doesn't get generated or it does not call .on('change', function() under which table generator code is present.
I'm not able to trigger that .on('change', function() for first dropdown but when user click on filter dropdowns that part works well
This answer is an extent to my last comment, as example.
//Put it into a seperate named function:
function fillTable() {
var d1 = $( "#session_id" ).val();
var d2 = $( "#start_date" ).val();
$("#tbody").empty();
for (var i = 0; i < obj1.length; i++) {
if (d1 && obj1[i][0] !== d1 && row > -1) continue;
if (d2 && obj1[i][1] !== d2 && row > -1) continue;
row++;
newTr.insertCell(-1).appendChild(document.createTextNode(obj1[i][0]));
newTr.insertCell(-1).appendChild(document.createTextNode(obj1[i][1]));
}
}
// reference to that function here
$("#choosefile, #session_id, #start_date").on('change', fillTable);
// call when the page is loading:
fillTable();

jquery seat chart PHP: store data price to mysql db

I have a php project that inserts the coordinates of the selected seats of a theater in a db msql.
This is the js file that draws the map and contains the variables.
var price = 0; //price
var $cart = $('#selected-seats'); //Sitting Area
var $counter = $('#counter'); //Votes
var $total = $('#total'); //Total money
var sc = $('#seat-map').seatCharts({
map: [ //Seating chart
'aaaaaaaaaa',
'aaaaaaa__a',
'aaaaaaaaaa',
'aaaaaaaaaa',
'aaaaaaabbb'
],
naming : {
top : true,
rows: ['A','B','C','D','E'],
getLabel : function (character, row, column) {
return column;
}
},
seats:{
a:{
price: 99.9
},
b:{
price: 200
}
},
legend : { //Definition legend
node : $('#legend'),
items : [
[ 'a', 'available', 'Option' ],
[ 'a', 'unavailable', 'Sold']
]
},
click: function () { //Click event
if (this.status() == 'available') { //optional seat
var maxSeats = 3;
var ms = sc.find('selected').length;
//alert(ms);
if (ms < maxSeats) {
price = this.settings.data.price;
$('<option selected>R'+(this.settings.row+1)+' S'+this.settings.label+'</option>')
.attr('id', 'cart-item-'+this.settings.id)
.attr('value', this.settings.id)
.attr('alt', price)
.data('seatId', this.settings.id)
.appendTo($cart);
$counter.text(sc.find('selected').length+1);
$counter.attr('value', sc.find('selected').length+1);
$total.text(recalculateTotal(sc));
$total.attr('value', recalculateTotal(sc));
return 'selected';
}
alert('You can only choose '+ maxSeats + ' seats.');
return 'available';
} else if (this.status() == 'selected') { //Checked
//Update Number
$counter.text(sc.find('selected').length-1);
$counter.attr('value', sc.find('selected').length-1);
//Delete reservation
$('#cart-item-'+this.settings.id).remove();
//update totalnum
$total.text(recalculateTotal(sc));
$total.attr('value', recalculateTotal(sc));
//Delete reservation
//$('#cart-item-'+this.settings.id).remove();
//optional
return 'available';
} else if (this.status() == 'unavailable') { //sold
return 'unavailable';
} else {
return this.style();
}
}
});
function number_format (number, decimals, decPoint, thousandsSep) { // eslint-disable-line camelcase
number = (number + '').replace(/[^0-9+\-Ee.]/g, '')
var n = !isFinite(+number) ? 0 : +number
var prec = !isFinite(+decimals) ? 0 : Math.abs(decimals)
var sep = (typeof thousandsSep === 'undefined') ? ',' : thousandsSep
var dec = (typeof decPoint === 'undefined') ? '.' : decPoint
var s = ''
var toFixedFix = function (n, prec) {
var k = Math.pow(10, prec)
return '' + (Math.round(n * k) / k)
.toFixed(prec)
}
// #todo: for IE parseFloat(0.55).toFixed(0) = 0;
s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.')
if (s[0].length > 3) {
s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep)
}
if ((s[1] || '').length < prec) {
s[1] = s[1] || ''
s[1] += new Array(prec - s[1].length + 1).join('0')
}
return s.join(dec)
}
// Add total money
function recalculateTotal(sc) {
var total = 0;
$('#selected-seats').find('option:selected').each(function () {
total += Number($(this).attr('alt'));
});
return number_format(total,2,'.','');
}
This file is viewed by a PHP file in a form like this
<div class="demo" style="margin-top:10px;min-width: 360px;">
<div id="seat-map">
<div class="front">SCREEN</div>
</div>
<div id="legend"></div>
</div>
<form role="form" id="myfrm2" action="book.php?id=<?php echo $FILM_ID; ?>" method="post">
<input type="hidden" name="session" value="<?php echo $session; ?>">
<input type="hidden" name="date" value="<?php echo $date; ?>">
<select class="form-control" style="display:block;" id="selected-seats" name="seat[]" multiple="multiple"></select>
<p>Tickets: <input id="counter" name="counter" readonly></input></p>
<p>Total: <b>€<input id="total" name="total" readonly></input></b></p>
<button type="submit" style="display: block; width: 100%;" name="book" value="book" class="btn btn-danger">Book</button>
</form>
<?php } ?>
</div>
All data are inserted into a DB mysql by this PHP file
<?php
if (isset($_POST['book'])) {
$date = $_POST["date"];
$session = $_POST["session"];
$counter = $_POST["counter"];
$total = $_POST["total"];
$user_id = $_SESSION["id"];
$film_id = $_GET['id'];
$seat = (isset($_POST['seat']) ? $_POST['seat']:array());
if (is_array($seat)) {
foreach ($seat as $selectedOption){
$query = "INSERT INTO booking(USER_ID, FILM_ID, BOOKING_SESSION, BOOKING_DATE, BOOKING_SEAT, BOOKING_PRICE, BOOKING_NUM)
VALUES ('$user_id','$film_id','$session','$date','$selectedOption','$total','$counter')";
$result = mysqli_query ($connection,$query)
or die ("<div class='alert alert-danger' role='alert'>You couldn't execute query</div>");
}
echo " <div class='alert alert-success' role='success'>
Congrats your booking has been done! Print the tickets <a href='./fpdf18/generate-pdf.php?film=$film_id' target='_blank'>here</a>!
</div>";
}
}
?>
Everything works correctly, all data are inserted in the DB !
But I have added a data to insert to the DB, the price SEAT_PRICE, so I have changed the "option selected" in the JS file to this
$('<option selected>R'+(this.settings.row+1)+' S'+this.settings.label+' P'+this.settings.data.price+'</option>')
the price (the tag in the console is "alt" is now visible on the page but I don't understand how to store this data to the DB.
Any suggestion is appreciated
OK after many attempts and posts in many forum, I have found my solution.
1) The JS file must be modified like that (passing 2 values):
$('<option selected>R'+(this.settings.row+1)+' S'+this.settings.label+' P'+this.settings.data.price+'</option>')
.attr('id', 'cart-item-'+this.settings.id)
.attr('value', this.settings.id + "|" + this.settings.data.price)
.attr('alt', price)
.data('seatId', this.settings.id)
.appendTo($cart);
2) the PHP file must be changed like that (dividing seat array - separated by "|" - to post the 2 values:
<?php
if (isset($_POST['book'])) {
$date = $_POST["date"];
$session = $_POST["session"];
$counter = $_POST["counter"];
$total = $_POST["total"];
$user_id = $_SESSION["id"];
$film_id = $_GET['id'];
$seat = (isset($_POST['seat']) ? $_POST['seat']:array());
if (is_array($seat)) {
foreach ($seat as $selectedOption){
$ar = explode('|',$selectedOption);
$query = "INSERT INTO booking(USER_ID, FILM_ID, BOOKING_SESSION, BOOKING_DATE, BOOKING_SEAT, SEAT_PRICE, BOOKING_PRICE, BOOKING_NUM)
VALUES ('$user_id','$film_id','$session','$date','$ar[0]','$ar[1]','$total','$counter')";
$result = mysqli_query ($connection,$query)
or die ("<div class='alert alert-danger' role='alert'>You couldn't execute query</div>");
}
echo " <div class='alert alert-success' role='success'>
Congrats your booking has been done! Print the tickets <a href='./fpdf18/generate-pdf.php?film=$film_id' target='_blank'>here</a>!
</div>";
}
}
?>

AJAX Delete multiple records with checkboxes

I'm performing multiple delete records operation using jQuery and php currently i'm able to delete single / multiple records by clicking on checkbox its working fine as of now but my page gets refreshed every time i delete record because im not using ajax.
I'm a beginner in ajax I want to perform this same operation using JQUERY/AJAX which will not make my page reload every time i delete my record so i want to use ajax for the same code so that i can handle my page reload.
Somebody help me out in achieving it Thanks!!
HTML/PHP
<form method="post" name="data_table">
<table id="table_data">
<tr>
<td>Name</td>
<td>Select All <input type="checkbox" id="check_all" value=""></td>
</tr>
<?php
$query = mysql_query("SELECT * FROM `products`");
while($row = mysql_fetch_array($query))
{
?>
<tr>
<td>
<?php echo $row['product_title']; ?>
</td>
<td>
<input type="checkbox" value="<?php echo $row['id'];?>" name="data[]" id="data">
</td>
</tr>
<?php
}
?>
</table>
<br />
<input name="submit" type="submit" value="Delete" id="submit">
</form>
JQuery
jQuery(function($)
{
$("form input[id='check_all']").click(function()
{
var inputs = $("form input[type='checkbox']");
for(var i = 0; i < inputs.length; i++)
{
var type = inputs[i].getAttribute("type");
if(type == "checkbox")
{
if(this.checked)
{
inputs[i].checked = true;
}
else
{
inputs[i].checked = false;
}
}
}
});
$("form input[id='submit']").click(function()
{ var inputs = $("form input[type='checkbox']");
var vals=[];
var res;
for(var i = 0; i < inputs.length; i++)
{
var type = inputs[i].getAttribute("type");
if(type == "checkbox")
{
if(inputs[i].id=="data"&&inputs[i].checked){
vals.push(inputs[i].value);
}
}
}
var count_checked = $("[name='data[]']:checked").length;
if(count_checked == 0)
{
alert("Please select a product(s) to delete.");
return false;
}
if(count_checked == 1)
{
res= confirm("Are you sure you want to delete these product?");
}
else
{
res= confirm("Are you sure you want to delete these products?");
}
if(res){
/*** This portion is the ajax/jquery post calling ****/
$.post("delete.php", {data:vals}, function(result){
$("#table_data").html(result);
});
}
});
});
PHP delete code
<?php
if(isset($_POST['data']))
{
$id_array = $_POST['data']; // return array
$id_count = count($_POST['data']); // count array
for($i=0; $i < $id_count; $i++)
{
$id = $id_array[$i];
$query = mysql_query("DELETE FROM `products` WHERE `id` = '$id'");
if(!$query)
{
die(mysql_error());
}
}?>
Please do the changes jquery as
jQuery(function($)
{
$("form input[id='check_all']").click(function()
{
var inputs = $("form input[type='checkbox']");
for(var i = 0; i < inputs.length; i++)
{
var type = inputs[i].getAttribute("type");
if(type == "checkbox")
{
if(this.checked)
{
inputs[i].checked = true;
}
else
{
inputs[i].checked = false;
}
}
}
});
$("form input[id='submit']").click(function()
{ var inputs = $("form input[type='checkbox']");
var vals=[];
var res;
for(var i = 0; i < inputs.length; i++)
{
var type = inputs[i].getAttribute("type");
if(type == "checkbox")
{
if(inputs[i].id=="data"&&inputs[i].checked){
vals.push(inputs[i].value);
}
}
}
var count_checked = $("[name='data[]']:checked").length;
if(count_checked == 0)
{
alert("Please select a product(s) to delete.");
return false;
}
if(count_checked == 1)
{
res= confirm("Are you sure you want to delete these product?");
}
else
{
res= confirm("Are you sure you want to delete these products?");
}
if(res){
/*** This portion is the ajax/jquery post calling ****/
$.post("delete.php", {data:vals}, function(result){
$("#table_data").html(result);
});
}
});
});
Delete.php as
<?php
if(isset($_POST['data']))
{
$id_array = $_POST['data']; // return array
$id_count = count($_POST['data']); // count array
for($i=0; $i < $id_count; $i++)
{
$id = $id_array[$i];
$query = mysql_query("DELETE FROM `test` WHERE `id` = '$id'");
if(!$query)
{
die(mysql_error());
}
}?>
<tr>
<td>ID</td>
<td>TITLE</td>
<td>Select All <input type="checkbox" id="check_all" value=""></td>
</tr>
<?php
$query = mysql_query("SELECT * FROM `test`");
while($row = mysql_fetch_array($query))
{
?>
<tr>
<td>
<?php echo $row['id']; ?>
</td>
<td>
<?php echo $row['name']; ?>
</td>
<td>
<input type="checkbox" value="<?php echo $row['id'];?>" name="data[]" id="data">
</td>
</tr>
<?php
} unset($row);
}

Sorting datatables with IP-Adresses and hyperlinks

My datatable was acting cool and all until I modified integer element of a particular column(with hyperlinks) to IP Adresses. All of a sudden the sorting feature was acting weird.
Before I had something like this :
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<script type="text/javascript" src="includes/js/jquery.js"></script>
<script type="text/javascript" src="includes/js/jquery.dataTables.js"></script>
<script type="text/javascript" charset="utf-8">
jQuery.fn.dataTableExt.oSort['intComparer-asc'] = function (a, b) {
var m = a.match(/^\<.*\>(\d+)\<.*\>/);
a = m[1];
var m = b.match(/^\<.*\>(\d+)\<.*\>/);
b = m[1];
var value1 = parseInt(a);
var value2 = parseInt(b);
return ((value1 < value2) ? -1 : ((value1 > value2) ? 1 : 0));
};
jQuery.fn.dataTableExt.oSort['intComparer-desc'] = function (a, b) {
var m = a.match(/^\<.*\>(\d+)\<.*\>/);
a = m[1];
var m = b.match(/^\<.*\>(\d+)\<.*\>/);
b = m[1];
var value1 = parseInt(a);
var value2 = parseInt(b);
return ((value1 < value2) ? 1 : ((value1 > value2) ? -1 : 0));
};
$(document).ready(function() {
$('#tableAsI').dataTable({
'aoColumnDefs': [
{ 'sType': 'intComparer', 'aTargets': [ 0, 1 ] }
]
});
});
</script>
<table class="table" id="tableAsI">
<thead> <tr class="infoo"> <th>N</th> <th>IP</th> </tr> </thead>
<tbody>
<?php
echo '<tr><td>2</td>';
echo '<td >13</td>';
echo'</tr>';
echo '<tr> <td>4</td>';
echo '<td >1</td>';
echo'</tr>';
echo '<tr><td>1</td>';
echo '<td >2</td>';
echo'</tr>';
echo '<tr><td>3</td>';
echo '<td >20</td>';
echo'</tr>';
?>
</tbody>
</table>
And the sorting works well, but after adding the IP Adresses i have this for example:
<td >100.130.6.109</td>
and the result is :
100.130.6.109
**100.130.6.11**
100.130.6.110
100.130.6.111
What i want is this :
**100.130.6.11**
100.130.6.109
100.130.6.110
100.130.6.111
Thanks.
How about using this plugin (or the code from it in the case of extra links support)? https://datatables.net/plug-ins/sorting/ip-address
The plugin uses the code like this:
var m = a.split("."), x = "";
But, because you also have the hyperlink, with a small help of jQuery, you can easily parse and extract the content of the link. For example:
$('100.130.6.109').html();
This will give you 100.130.6.109 exactly. Thus, the small modification to the plugin code would look like this:
jQuery.extend(jQuery.fn.dataTableExt.oSort, {
"ip-address-pre": function(a) {
var ip_address = $(a).html();
var m = ip_address.split("."), x = "";
...

Clone Table Row Not Working

I am having a weird problem. I am creating a metabox for wordpress and came across an issue where a <tr> will not clone on .click. I am using a while php loop and can get div, p, a, etc tags to clone but not luck with the table. Here is a look at the code.
<?php while($mb->have_fields_and_multi('ingredients')) : ?>
<?php $mb->the_group_open(); ?>
<tr>
<td>Blah</td>
</tr>
<?php $mb->the_group_close(); ?>
<?php endwhile; ?>
add row
Here is the javascript
$('[class*=docopy-]').click(function(e)
{
e.preventDefault();
var p = $(this).parents('.postbox'); /*wp*/
var the_name = $(this).attr('class').match(/docopy-([a-zA-Z0-9_-]*)/i)[1];
var the_group = $('.wpa_group-'+ the_name +'.tocopy', p).first();
var the_clone = the_group.clone().removeClass('tocopy last');
var the_props = ['name', 'id', 'for', 'class',];
the_group.find('*').each(function(i, elem)
{
for (var j = 0; j < the_props.length; j++)
{
var the_prop = $(elem).attr(the_props[j]);
if (the_prop)
{
var the_match = the_prop.match(/\[(\d+)\]/i);
if (the_match)
{
the_prop = the_prop.replace(the_match[0],'['+ (+the_match[1]+1) +']');
$(elem).attr(the_props[j], the_prop);
}
the_match = null;
// todo: this may prove to be too broad of a search
the_match = the_prop.match(/n(\d+)/i);
if (the_match)
{
the_prop = the_prop.replace(the_match[0], 'n' + (+the_match[1]+1));
$(elem).attr(the_props[j], the_prop);
}
}
}
});
if ($(this).hasClass('ontop'))
{
$('.wpa_group-'+ the_name, p).first().before(the_clone);
}
else
{
the_group.before(the_clone);
}
checkLoopLimit(the_name);
$.wpalchemy.trigger('wpa_copy', [the_clone]);
});
});
I apologize for the amount of javascript and I couldn't replicate the problem just jsfiddle.

Categories