DataTables Not Applying per page filtering - javascript

I'm attempting to use DataTables Server Side Processing
Currently I'm getting 1000 rows back (as display) even though the display is set to 10, 25, etc
jQuery:
$(document).ready(function() {
$('#paginatedTableSS').dataTable( {
"processing": true,
"serverSide": true,
"ajax": "script.php"
} );
} );
script.php:
$i = 0;
$test = array();
$test['draw'] = 1;
$test['recordsTotal'] = 200000;
$test['recordsFiltered'] = 8;
$test['data'] = array();
while($i<=20){
array_push($test['data'], ['test1 ' . $i, 'test2 ' . $i, 'test3 ' . $i, 'test4 ' . $i]);
$i=$i+1;
}
echo json_encode($test);
My ultimate goal is to pass along start to the script so the script can use that to give the correct data back. But currently I need to fix the above before moving forward I think. But I'm not sure what's wrong with it or how to debug it.

aaData seems to indicate that you're using the legacy datatables. If that's the case, you're missing iTotalRecords, iTotalDisplayRecords and sEcho.
$test['iTotalRecords'] = count($test['aaData']);
$test['iTotalDisplayRecords'] = count($test['aaData']);
$test['Echo'] = $_REQUEST['sEcho'];
see http://legacy.datatables.net/usage/server-side
if you're not using the legacy datatables you need to use data, records and recordsFiltered instead (as referenced in your link)
Edit
The reason your table is displaying 1000 rows is because that's the # of rows you're returning. Use the length and start parameters to determine which rows to return i.e
$start = (isset($_REQUEST['start']) && is_numeric($_REQUEST['start']))
? $_REQUEST['start'] : 0;
$length = (isset($_REQUEST['length']) && is_numeric($_REQUEST['length']))
? $_REQUEST['length'] : 100;
$test = array('data'=>array(), 'recordsTotal', 'draw', 'recordsFiltered');
for($i=$start; $i<=$length; $i++) {
array_push($test['data'], array('id'=>$i,'date'=>$i,'status'=>$i,'options'=>$i));
}
$test['recordsTotal'] = 200000;
$test['draw'] = 1;
$test['recordsFiltered'] = count($test['data']);
echo json_encode($test);

Related

(populate dropdown in contact form 7 getting this error - Warning: array_keys() expects parameter 1 to be array, null given in

Ok where to start, I will try and explain as much as I can.
I am using wordpress with contact form 7 and I am trying to populate 3 dropdown items on the contact form, I found some code that I was able to use with no problem but the problem with this was that it was getting the information from a excel file, the file is now to big and will not run on my website anymore so I would like to get the information from my database now.
I have made a table in my database "vehicle_information" with 3 columns "vehicle_type", "vehicle_make", vehicle_model"
I have code in my functions.php and code in my footer to be able to use the cf7 shortcodes.
Code from funtions.php
function ajax_cf7_populate_values() {
//MySQLi information
$db_host = '***';
$db_username = '***';
$db_password = '***';
$vehicles_makes_models = array();
//connect to mysqli database (Host/Username/Password)
$connection = mysqli_connect($db_host, $db_username, $db_password) or die('Error ' . mysqli_error());
//select MySQLi dabatase table
$vehicles_makes_models = mysqli_select_db($connection, 'vehicle_information') or die('Error ' . mysqli_error());
$sql = mysqli_query($connection, 'SELECT * FROM vehicle_type');
while($row = mysqli_fetch_array($sql)) {
$vehicles_makes_models[$row[0]][$row[1]][] = $row[2]; }
}
// setup the initial array that will be returned to the the client side script as a JSON object.
$return_array = array(
'vehicles' => array_keys($vehicles_makes_models),
'makes' => array(),
'models' => array(),
'current_vehicle' => false,
'current_make' => false
);
// collect the posted values from the submitted form
$vehicle = key_exists('vehicle', $_POST) ? $_POST['vehicle'] : false;
$make = key_exists('make', $_POST) ? $_POST['make'] : false;
$model = key_exists('model', $_POST) ? $_POST['model'] : false;
// populate the $return_array with the necessary values
if ($vehicle) {
$return_array['current_vehicle'] = $vehicle;
$return_array['makes'] = array_keys($vehicles_makes_models[$vehicle]);
if ($make) {
$return_array['current_make'] = $make;
$return_array['models'] = $vehicles_makes_models[$vehicle][$make];
if ($model) {
$return_array['current_model'] = $model;
}
}
}
// encode the $return_array as a JSON object and echo it
echo json_encode($return_array);
wp_die();
// These action hooks are needed to tell WordPress that the cf7_populate_values() function needs to be called
// if a script is POSTing the action : 'cf7_populate_values'
add_action( 'wp_ajax_cf7_populate_values', 'ajax_cf7_populate_values' );
add_action( 'wp_ajax_nopriv_cf7_populate_values', 'ajax_cf7_populate_values' );
Code from my footer
<script>
(function($) {
// create references to the 3 dropdown fields for later use.
var $vehicles_dd = $('[name="vehicles"]');
var $makes_dd = $('[name="makes"]');
var $models_dd = $('[name="models"]');
// run the populate_fields function, and additionally run it every time a value changes
populate_fields();
$('select').change(function() {
populate_fields();
});
function populate_fields() {
var data = {
// action needs to match the action hook part after wp_ajax_nopriv_ and wp_ajax_ in the server side script.
'action' : 'cf7_populate_values',
// pass all the currently selected values to the server side script.
'vehicle' : $vehicles_dd.val(),
'make' : $makes_dd.val(),
'model' : $models_dd.val()
};
// call the server side script, and on completion, update all dropdown lists with the received values.
$.post('<?php echo admin_url( 'admin-ajax.php' ) ?>', data, function(response) {
all_values = response;
$vehicles_dd.html('').append($('<option>').text(' -- choose vehicle -- '));
$makes_dd.html('').append($('<option>').text(' -- choose make -- '));
$models_dd.html('').append($('<option>').text(' -- choose model -- '));
$.each(all_values.vehicles, function() {
$option = $("<option>").text(this).val(this);
if (all_values.current_vehicle == this) {
$option.attr('selected','selected');
}
$vehicles_dd.append($option);
});
$.each(all_values.makes, function() {
$option = $("<option>").text(this).val(this);
if (all_values.current_make == this) {
$option.attr('selected','selected');
}
$makes_dd.append($option);
});
$.each(all_values.models, function() {
$option = $("<option>").text(this).val(this);
if (all_values.current_model == this) {
$option.attr('selected','selected');
}
$models_dd.append($option);
});
},'json');
}
})( jQuery );
The problem is I am still learning and this is the first time I have had to use this funtion.
and I am getting an error on my website
Warning: array_keys() expects parameter 1 to be array, null given in /customers/4/0/0/motobid.co.uk/httpd.www/wp-content/themes/storevilla-child/functions.php on line 38 {"vehicles":null,"makes":[],"models":[],"current_vehicle":false,"current_make":false}
any help would be very greatful.
Just like to say code was supplied by BDMW.
Where you use the method array_keys(), instead of:
$return_array['makes'] = array_keys($vehicles_makes_models[$vehicle]);
Try this:
$return_array['makes'] = ! empty($vehicles_makes_models[$vehicle]) ? array_keys($vehicles_makes_models[$vehicle]) : [];
From what I've read, the array_keys() has been an issue depending on php versions. Hope this helps!

Sending data to url through post to export to excel using javascript

I have a reporting website that I use DataTables Server Side Processing on. Everything works great except that I need to be able to export the whole data set and not just the part that is showing on the screen. I have reports that have 10,000+ rows and 65+ columns so showing the whole report on the page is out of the question (would take more than 5 minutes and then time out). I've gotten really close to an answer, I think, but need help getting the rest of the way. Here's what I've got:
I'm collecting the data that I need sending it to a file that uses PHPExcel libraries to export an Excel file.
When I navigate to the file (ExportAllToExcel.php) it works fine, but when I use a button to send the data to the file there is no download. Here's what I've got going right now:
$.fn.dataTable.ext.buttons.export =
{
className: 'buttons-alert',
id: 'ExportButton',
text: "Export All Test III",
action: function (e, dt, node, config)
{
var SearchData = dt.rows({ filter: 'applied' }).data();
var OrderData = dt.order();
var NumRow = SearchData.length;
var SearchData2 = [];
for (j = 0; j < NumRow; j++)
{
var NewSearchData = SearchData[j];
for (i = 0; i < NewSearchData.length; i++)
{
NewSearchData[i] = NewSearchData[i].replace("<div class='Scrollable'>", "");
NewSearchData[i] = NewSearchData[i].replace("</div>", "");
}
SearchData2.push([NewSearchData]);
}
for (i = 0; i < SearchData2.length; i++)
{
for (j = 0; j < SearchData2[i].length; j++ )
{
SearchData2[i][j] = SearchData2[i][j].join('::');
}
}
SearchData2 = SearchData2.join("%%");
//var SendPageData = new XMLHttpRequest();
//SendPageData.open("POST", "./ExportAllToExcel.php", true);
//SendPageData.send('{NumRow=' + NumRow + '},{SearchData=' + SearchData2 + '}');
$.post('./ExportAllToExcel.php',{SearchData: SearchData2,NumRow: NumRow});
window.location.href = './ExportAllToExcel.php';
}
};
This doesn't work. The $.POST sends the data and gets a response, but does not export the file.
The Window.location goes to the file and exports to Excel but doesn't have the data from $_POST so the file only has headers.
And the SendPageData does the same as the $.POST sends the data and gets a response, but doesn't create the file.
And here's the ExportAllToExcel.php:
<?php
require $_SERVER['DOCUMENT_ROOT'].'/dev/Location/Helper/PageName.php'; //Pulls the Page name and Table name and returns the $SQLTableName, $TableName, $Title, $Page and $HeadingDesc
include $_SERVER['DOCUMENT_ROOT'].'/dev/Location/DBConn.php'; //DB connection info
$headings = array(); //Create the empty array for use later and so that it won't throw an error if not assinged later
$hsql = "select Headings from TableHeadings where TableName = '$TableName' order by Id"; //Get all the column headers from the TableHeadings table in SQL
$getHeadings = $conn->query($hsql);
$rHeadings = $getHeadings->fetchALL(PDO::FETCH_ASSOC);
$CountHeadings = count($rHeadings); //Count how many columns that there will be
$tsqlHeadings = '';
$ColumnHeader = array();
for ($row = 0; $row < $CountHeadings; $row++)
{
$headings[$row] = $rHeadings[$row]["Headings"]; //fill the array of column headings for use in creating the DataTable
}
print_r($headings);
// Error reporting
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
if (PHP_SAPI == 'cli')
die('This example should only be run from a Web Browser');
// Add some data
$ColumnArray = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ');
//$HeadingArray = array('Year','Quater','Country','Sales');
$HeadingArray = $headings;
$primaryKey = 'id';
$table = $SQLTableName;
$request = $_POST;
$dataArray = array();
$dataArraystr = explode('%%',$_POST['SearchData']);
foreach($dataArraystr as $ArrayStr)
{
$dataArray[] = explode('::',$ArrayStr);
}
// Include PHPExcel
require_once dirname(__FILE__) . './Classes/PHPExcel.php';
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
// Set document properties
$objPHPExcel->getProperties()->setCreator("Michael McNair")
->setLastModifiedBy("Michael McNair")
->setTitle($TableName)
->setSubject($TableName)
->setDescription("Report for " .$TableName. " using PHPExcel, generated using PHP classes.")
->setKeywords("office PHPExcel php " . $TableName)
->setCategory("Report Export File");
$objPHPExcel->getActiveSheet()->fromArray($HeadingArray, NULL, 'A1');
$objPHPExcel->getActiveSheet()->fromArray($dataArray, NULL, 'A2');
$CountOfArray = count($HeadingArray);
// Set title row bold
$objPHPExcel->getActiveSheet()->getStyle('A1:' .$ColumnArray[$CountOfArray-1]. '1')->getFont()->setBold(true);
// Set autofilter
// Always include the complete filter range!
// Excel does support setting only the caption
// row, but that's not a best practise...
$objPHPExcel->getActiveSheet()->setAutoFilter($objPHPExcel->getActiveSheet()->calculateWorksheetDimension());
// Rename worksheet
$objPHPExcel->getActiveSheet()->setTitle('SimpleTest');
// Add a second sheet, but infront of the existing sheet
//$myWorkSheet = new PHPExcel_Worksheet($objPHPExcel,'New Worksheet');
//$objPHPExcel->addSheet($myWorkSheet,0);
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);
// Redirect output to a client’s web browser (Excel2007)
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="ExportAllToExcelTest.xlsx"');
header('Cache-Control: max-age=0');
// If you're serving to IE 9, then the following may be needed
header('Cache-Control: max-age=1');
// If you're serving to IE over SSL, then the following may be needed
header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
header ('Pragma: public'); // HTTP/1.0
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
///$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
ob_clean();
$objWriter->save('php://output');
?>
I have fixed the problem. This is the button now:
$.fn.dataTable.ext.buttons.export =
{
className: 'buttons-alert',
id: 'ExportButton',
text: "Export All To Excel",
action: function (e, dt, node, config)
{
window.location.href = './ServerSide.php?ExportToExcel=Yes';
}
};
I use just the one $_GET and send that to my ServerSide.php file, the same file that gets the data for the browser, to begin with. There I now check for that and use my KeepPost.php file to keep the filtering and sorting that the user has placed on the report:
<?php
if( isset($_POST['draw']))
{
include 'DBConn.php';
//echo "Here";
//print_r($_POST);
$KeepPost = $_POST;
$KeepPost['length'] = -1;
$PostKept = serialize($KeepPost);
$TSQL = "UPDATE PostKept set Value = '" .$PostKept. "'";
$sth = $conn->prepare($TSQL);
//print_r($sth);
$sth->execute();
}
?>
Then in ServerSide.php I check for the $_GET['ExportToExcel']:
if (isset($_GET['ExportToExcel']) && $_GET['ExportToExcel'] == 'Yes')
{
$GetSQL = "Select Value from PostKept";
$KeepResult = $conn->query($GetSQL);
$KeepResults = $KeepResult->fetchALL(PDO::FETCH_ASSOC);
//print_r($KeepResults);
error_log(date("Y/m/d h:i:sa")." KeepResults: " .$KeepResults[0]['Value']. "\n",3,"C:\Temp\LogPHP.txt");
//findSerializeError($_COOKIE['KeepPost']);
//print_r($_COOKIE);
$request = unserialize($KeepResults[0]['Value']);
//echo "<br>Request: "; print_r($request);
$DataReturn = json_encode(FilterSort::complex($request,$sqlConnect,$table,$primaryKey,$ColumnHeader,1));
//echo "DataReturn:<br>"; print_r($DataReturn);
require './ExportAllToExcel.php';
}
This then sends the correct data to the ExportAllToExcel.php file and exports the data the users wants.

How to loop through the ajax function and retrieve result from database by looping order

I'm doing a website. In this website i have to show the temperature of each sensor devices. Image of the sensor details. I'm getting these sensor information by looping through php. Now, i want to make them live. Which means i want to show the live temperature rate for each devices. I have done some coding part without looping the whole device via ajax call. I'm storing the device information in ul li tags. Image of ul li. Here you can see each li represents own 'device-code' and 'site-page' (in this case 'site-page' is same). Now I want to loop each li and retrieve temperature value according to each 'device-code' and 'site-page'.
And this is my jquery/ajax function :
setInterval(function() {
var lis = $('#ul-devices li').length;
for(x=0; x<lis; x++){
var site_device_code = $('#ul-devices li:nth-child('+ (x+1) +')').data('device-code');
var sitePageId = $('#ul-devices li:nth-child('+ (x+1) +')').data('site-page')
$.ajax({
url: 'sitefunction.php',
type: 'post',
data: { 'sitePageId' : sitePageId, 'device_code' : site_device_code },
success:function(data){
console.log(sitePageId);
console.log(site_device_code);
console.log(data.temp_value);
}
});
}
}, 1000);
Now this is my php function(sitefunction.php) :
require_once 'inc/core/init.php';
$db = DB::getInstance();
if(Input::get('sitePageId') && Input::get('device_code')) {
$sitePageId = Input::get('sitePageId');
$device_code = Input::get('device_code');
$sensorsInfo = $db->sqlQuery("SELECT * FROM `device_info` WHERE `site_code` = {$sitePageId} AND `device_code` = {$device_code}");
while($sensor = $sensors->fetch(PDO::FETCH_OBJ)){
$temp_value = $sensor->value;
$last_updated = $sensor->last_updated;
};
$result = array(
'temp_value' => $temp_value,
'last_updated' => $last_updated
);
echo json_encode($result);
}
Here $db represents the database connection class.
Now the problem is when i run this code the result is, the result image here you can see following values is repeating,
1 (sitePageId)
8627334 (last li tag's device_code)
undefined (data.temp_value)
i want the result should be like this (in console),
1 (sitePageId)
312169 (device_code)
34 (data.temp_value)
1
13618979
255
1
312890
33.25
1
8627813
41
1
8627334
23
If anyone knew how to solve this, Please help me sort it out.
Updated
this is my jquery code:
setInterval(function() {
var lis = $('#ul-devices li').length;
for(x=0; x<lis; x++){
var site_device_code = $('#ul-devices li:nth-child('+ (x+1) +')').data('device-code');
var sitePageId = $('#ul-devices li:nth-child('+ (x+1) +')').data('site-page')
$.ajax({
url: 'sitefunction.php',
type: 'post',
data: { 'sitePageId' : sitePageId, 'device_code' : site_device_code },
success:function(data){
for( var d in data ){
console.log(d.site_code); //site_code,device_code,value are database field names
console.log(d.device_code);
console.log(d.value);
}
}
});
}
}, 1000);
This is my php code:
require_once 'inc/core/init.php';
$db = DB::getInstance();
if(Input::get('sitePageId') && Input::get('device_code')) {
$sitePageId = Input::get('sitePageId');
$device_code = Input::get('device_code');
$sensors = $db->sqlQuery("SELECT * FROM `device_info` WHERE `site_code` = {$sitePageId} AND `device_code` = {$device_code}");
$rows = array();
while($sensor = $sensors->fetch(PDO::FETCH_ASSOC)){
$rows[] = $sensor;
};
echo json_encode($rows);
}
This is my database table :
Updated result
Use Jquery to loop on controls solve your problem
$('#ul-devices li').each(function(i, n){
console.log("device=" + $(n).data("device-code") + ", page=" + $(n).data("site-page"));
});
You will need a multi-dimensional return array, currently you are returning only data for the last record. you'll need to change this
while($sensor = $sensors->fetch(PDO::FETCH_OBJ)){
//these variables are overwritten on each itteration
$temp_value = $sensor->value;
$last_updated = $sensor->last_updated;
};
//Those 2 vars only contain the last row now...
//results here is a single dimensional array of only one row.
$result = array(
'temp_value' => $temp_value,
'last_updated' => $last_updated
);
Each loop in the above while overwrites those two variables, so at the end of the loop you only get the last record in the DB result set, mainly because you access the variables outside of the loop. So you need to change it to:
$rows = array();
while($row = $sensors->fetch(PDO::FETCH_ASSOC)){
$rows[] = $row;
};
echo json_encode($rows);
By using FETCH_ASSOC you don't need to convert it to an array. Your array should look something like this ( after the loop )
$rows = array(
array( 'sitePageId'=>1, 'device_code' => 312169, 'temp_value' => 34 ),
array( 'sitePageId'=>1, 'device_code' => 4445455, 'temp_value' => 27),
....
);
Instead of this ( original data )
$results = array( 'sitePageId'=>1, 'device_code' => 312169, 'temp_value' => 34 );
Then in the JS success callback you can do something like this:
success:function(data){
for( var d in data ){
console.log(d.sitePageId);
console.log(d.device_code);
console.log(d.temp_value);
}
}
Because your Json will be like this
[
{ sitePageId:1, device_code:312169, temp_value:34 },
{ sitePageId:1, device_code:4445455, temp_value:27},
....
]
Provided the query returns these fields sitePageId, device_code, temp_value I think you don't have sitePageId in there but you get the Idea I am sure. Basically just unwrap the multi-dimensional array.

Pagination of table data from json

I want to paginate results obtained thusly:
function processResponse(response){
var myObj = JSON.parse(response);
var weighInData = myObj["WEIGH-INS"];
var weights = []; // re: weigh-in count and calculating highest/lowest
var userDisplayEl1 = document.getElementById("user-display-weigh-in-data");
var weighInCountEl = document.getElementById("weigh-in-count");
var weightLowEl = document.getElementById("weight-low");
var weightHighEl = document.getElementById("weight-high");
var weightgoalEl = document.getElementById("weight-goal");
var dataRows = document.getElementById("data-rows");
userDisplayEl1.innerHTML = "";
weighInCountEl.innerHTML = "";
weightLowEl.innerHTML = "";
weightHighEl.innerHTML = "";
weightgoalEl.innerHTML = "";
dataRows.innerHTML = "";
for (var obj in weighInData) {
if (weighInData[obj].user === selUser) {
weights.push(weighInData[obj].weight);
var row = "<tr>" +
"<td class=\"date\">" + weighInData[obj].date + " </td>" +
"<td class=\"value\">" + weighInData[obj].weight + "</td>" +
"</tr>";
dataRows.innerHTML += row;
// pagination here?
} // if ... === selUser
} // for var obj in weighInData
var weighInCount = weights.length;
var weightLowest = Math.min.apply(null, weights);
var weightHighest = Math.max.apply(null, weights);
userDisplayEl1.innerHTML = weighInData[obj].user + "'s weigh-ins:";
weightLowEl.innerHTML += weightLowest;
weightHighEl.innerHTML += weightHighest;
weighInCountEl.innerHTML = weighInCount;
} // processResponse
It seems that, because I'm executing Math on the results (after the for loop), I cannot use a limit in my db query, else the math would be inaccurate (executing only on the chunks of data, and not on the entirety of the data). So it seems I'll have to paginate on the client, but I have no idea how to proceed given how I'm currently loading/displaying the data. I have looked briefly at a couple of pagination plugins but since I wasn't clear on how to implement them given my extant code, I prefer the learning curve of achieving this w/out a plugin (or jQuery).
Any suggestions/pushes in the right direction, with the assumption that I con't substantively alter what I have now (which works, and which I understand, will be most appreciated.
Btw, my server-side code, fwiw:
$table = "`WEIGH_IN_DATA`";
if ($mysqli) {
$user = $_GET['selUser'];
$i = 0;
$jsonData = '{"WEIGH-INS": [';
$stmt = $mysqli->stmt_init();
$query = "SELECT * FROM $table WHERE USER = '$user'";
$result = $mysqli->query($query) or die("Error in the query (?)" . mysqli_error($mysqli));
while($row = mysqli_fetch_array($result)) {
$i++;
$user = $row["USER"];
$date = $row["DATE"];
$weight = $row["WEIGHT"];
$jsonData .= '{"user": "'.$user.'", "date": "'.$date.'", "weight": "'.$weight.'" },';
}
$jsonData = chop($jsonData, ","); // kill the trailing comma
$jsonData .=']}';
echo $jsonData;
}
Thank you,
svs
To save time, using a plug-in might be your best bet. I'm sure there are tutorials on building your own pagination plug-in on the internet which you can google.
I picked a random jQuery pagination plug-in (datatables), appended some data via js (similar to your code), then called the plug-in on the result table. Something like this may/may not work for you. Also, this is dependent on jQuery, and I'm not sure if you can include this library or not on your website.
Here's an example using dataset and jquery: http://codepen.io/anon/pen/IbBxf
Link to datatables: http://www.datatables.net/
$(document).ready(function(){
// append some data to an existing table in the DOM
for (var i =0 ; i < 10; i++) {
var $nr = $('<tr><td>A-' + i + '</td><td>B-' + i + '</td></tr>');
$('#myTable').append($nr);
}
// after table is populated, initiate plug-in and point to table
$('#myTable').DataTable(
{ "lengthMenu": [[5, 10, -1], [5, 10, "All"]] });
});
If you can't use jQuery:
Vanilla JS: It looks like this library can do pagination, however you'll need to read through the docs:
http://listjs.com/docs/plugins/pagination
This link also looks promising for your case (vanilla JS only):
http://www.tekgarner.com/simple-pagination-using-javascript/
HTML/CSS: If you don't need a lot of features, maybe you could also look at just adding a scrollbar to your HTML table results.
How to display scroll bar onto a html table

PHP validation to check if record exists

I'm trying to create a validation for a form. When a user fills out the form, it is supposed to run a set of queries. The first is to check if a records already exists in the table. If it does exist, then it doesn't need to run the the next 2 queries, which are to INSERT and UPDATE.
I'm not sure what I am doing wrong, but the table already has an existing record. After checking the table, it still runs the INSERT and UPDATE queries. They should not fire. It should not do anything.
Here is my code: * I'm starting my code from the for loop, which is just taking an array of BOL numbers and CONTAINER numbers that the user manually selected. I exploded the array, but I will not show that code as I do not think it is necessary to show in this case *
<?php
for($i = 0; $i < $count; $i++)
{
$bolService = $bolArray[$i];
$conService = $conArray[$i];
$checkService = "SELECT * FROM import_service WHERE bol = '" . $bolService . "' AND container = '" . $conService . "'";
$checkSerRes = mysql_query($checkService);
$checkSerNum = mysql_num_rows($checkSerRes);
if($checkSerNum > 0)
{
$successService = false;
}
elseif($checkSerNum = 0)
{
$sql_query_string = mysql_query
("INSERT INTO import_service (bol, container) VALUES ('$bolService','$conService')");
$updateService = mysql_query ("UPDATE import_dispatch_details SET SERVICE = 'Y'
WHERE BOL_NUMBER = '$bolService' AND CONTAINER = '$conService')");
$successService = true;
}
}
// javascript fires an ALERT message in this next set of code
if($successService = true)
{
echo ("<script language='javascript'>
window.alert('Record has been saved')
window.location.href=''
</script>");
}
// if checkSerNum > 0, then it should skip the INSERT and UPDATE and fire the code below
elseif($successService = false)
{
echo ("<script language='javascript'>
window.alert('There was an error saving the record')
window.location.href=''
</script>");
}
?>
I'm not sure why this is not working correctly. I need this validation to work. I'm sure there is an alternative method, but this is what I got.
Please help me make this work.
Thank you in advance.
This elseif($checkSerNum = 0) needs to be elseif($checkSerNum == 0)
You're presently doing an assignment instead of a comparison.
Including if($successService = true) and elseif($successService = false) so add another = sign.
Add error reporting to the top of your file(s) which will help during production testing.
error_reporting(E_ALL);
ini_set('display_errors', 1);
http://www.php.net/manual/en/function.mysql-error.php
Footnotes:
mysql_* functions deprecation notice:
http://www.php.net/manual/en/intro.mysql.php
This extension is deprecated as of PHP 5.5.0, and is not recommended for writing new code as it will be removed in the future. Instead, either the mysqli or PDO_MySQL extension should be used. See also the MySQL API Overview for further help while choosing a MySQL API.
These functions allow you to access MySQL database servers. More information about MySQL can be found at » http://www.mysql.com/.
Documentation for MySQL can be found at » http://dev.mysql.com/doc/.
This isn't quite efficient (you are selecting * from your table, which you aren't using - waste of memory?). Why don't you do something like this:
for ($i = 0; $i < $count; $i++)
{
$bolService = $bolArray[$i];
$conService = $conArray[$i];
$recordExists = false;
$result = mysql_query("SELECT COUNT(*) AS recordCount FROM import_service WHERE bol = '" . $bolService . "' AND container = '" . $conService . "'");
if ($result) {
$row = mysql_fetch_assoc($result);
$recordExists = ($row['recordCount'] >= 1);
}
if ($recordExists)
{
$successService = false;
}
else
{
$sql_query_string = mysql_query
("INSERT INTO import_service (bol, container) VALUES ('$bolService','$conService')");
$updateService = mysql_query
("UPDATE import_dispatch_details SET SERVICE = 'Y'
WHERE BOL_NUMBER = '$bolService' AND CONTAINER = '$conService')");
$successService = true;
}
}
P.S. mysql_* is officially deprecated. Please use PDO or MySQLi. Also, your code is potentially open to SQL Injection.

Categories