yadcf server side, column dropdown select and cumulative filtering - yadcf

Select DropDown ImageEpisode 2
I’ve update the DataTables php code to search and collect the data that is add or reduce the json data that is used by yadcf. How do I prevent yadcf on updating that column list of options values if a value is already selected to the filter? When I reselect the filter all of the previous options are removed, which I don’t want if someone selects the wrong option. I would have use the below if to prevent that select to update. Also, the reset button is not an option I want to use.
if ( strindex[w] === 3 && GBselBoxphp3 === '' ) {
var selectoptdata = data.yadcf_data_3;
select.empty().append('<option value=""/>');
$.each(selectoptdata, function (i, j) {
select.append( '<option value="'+j+'">'+j+'</option>' )
});
}
Episode 1
The solution that you had obtained from Allan Jardine to populate column dropdown had cleared one more hurdle so I can implement server-side processing to my DataTables, but adding the changes mentioned below to ssp.class.php has impaired cumulative filtering. Cumulative filtering a very useful feature when narrowing down a selected record. Any idea how this could be corrected?
stackoverflow.com/questions/41507443/yadcf-datatables-server-side-populate-select-with-php
$data=SSP::simple( $_POST, $sql_details, $table, $primaryKey, $columns);
$db = SSP::sql_connect( $sql_details );
$stmt3 = $db->prepare( 'SELECT DISTINCT(value) FROM table' );
$stmt3->execute();
$data['yadcf_data_3'] = $stmt3->fetchAll(PDO::FETCH_COLUMN, 0);
$stmt5 = $db->prepare( 'SELECT DISTINCT(value2) FROM table' );
$stmt5->execute();
$data['yadcf_data_5'] = $stmt5->fetchAll(PDO::FETCH_COLUMN, 0);
$stmt6 = $db->prepare( 'SELECT DISTINCT(value3) FROM table' );
$stmt6->execute();
$data['yadcf_data_6'] = $stmt6->fetchAll(PDO::FETCH_COLUMN, 0);
echo json_encode($data);
This is what I have done to the php code to column 3. This also take in the value entered into the search box from Datatables.
if( !empty($requestData['columns'][3]['search']['value']) ){
$strselBoxphp3 = $requestData['columns'][3]['search']['value'];
} else {
$strselBoxphp3 = "";
}
//Column 3 DropDown Data
$db=SSP::sql_connect( $sql_details );
if( !empty($strsrchBoxvaluephp) ) {
$sql = ' SELECT DISTINCT SVD_Description FROM SVD_Equipment WHERE';
$sql .= ' (SVDid LIKE "%'.$strsrchBoxvaluephp.'%"';
$sql .= ' OR Audit LIKE "%'.$strsrchBoxvaluephp.'%"';
$sql .= ' OR SVD_Description LIKE "%'.$strsrchBoxvaluephp.'%"';
$sql .= ' OR Manufacture LIKE "%'.$strsrchBoxvaluephp.'%"';
$sql .= ' OR Model LIKE "%'.$strsrchBoxvaluephp.'%"';
$sql .= ' OR VIN LIKE "%'.$strsrchBoxvaluephp.'%"';
$sql .= ' OR State LIKE "%'.$strsrchBoxvaluephp.'%"';
$sql .= ' OR License_Plate_Number LIKE "%'.$strsrchBoxvaluephp.'%"';
$sql .= ' OR License_Plate_Expiration_Date LIKE "%'.$strsrchBoxvaluephp.'%"';
$sql .= ' OR Last_Inspection_Date LIKE "%'.$strsrchBoxvaluephp.'%"';
$sql .= ' OR Primary_Tech LIKE "%'.$strsrchBoxvaluephp.'%"';
$sql .= ' OR Manager LIKE "%'.$strsrchBoxvaluephp.'%")';
} else {
$sql = 'SELECT DISTINCT SVD_Description FROM SVD_Equipment WHERE SVD_Description != ""';
}
if( !empty($strselBoxphp2) ) {
$sql .= ' AND Audit = "'.$strselBoxphp2.'"';
}
if( !empty($strselBoxphp4) ) {
$sql .= ' AND Manufacture = "'.$strselBoxphp4.'"';
}
if( !empty($strselBoxphp5) ) {
$sql .= ' AND Model = "'.$strselBoxphp5.'"';
}
if( !empty($strselBoxphp11) ) {
$sql .= ' AND Primary_Tech = "'.$strselBoxphp11.'"';
}
if( !empty($strselBoxphp12) ) {
$sql .= ' AND Manager = "'.$strselBoxphp12.'"';
}
$sql .= ' ORDER BY SVD_Description;';
$stmt3 = $db->prepare($sql);
$stmt3->execute();
$data['yadcf_data_3'] = $stmt3->fetchAll(PDO::FETCH_COLUMN, 0);

Related

Display In stock available variations in WooCommerce single product

I have variable products with many variations where only a few items are actually In Stock while the majority of other variations are ''available on backorder''
I would like to be able to display a quick list of ONLY the items that are IN STOCK in the short product description of each product page so the customer doesn't have to try all variations one-by-one to finally find out which ones are in stock.
add_filter( 'woocommerce_short_description', 'display_in_stock_variations_to_short_description' );
function display_in_stock_variations_to_short_description( $excerpt ){
global $product;
if ( ! is_product() || empty($product) || ! is_a( $product, 'WC_Product' ) )
return $excerpt;
if( $product->is_type('variable') ) {
// Loop through visible children
foreach( $product->get_children() as $variation_id ) {
$variation = wc_get_product( $variation_id );
// Hide out of stock variations if 'Hide out of stock items from the catalog' is checked.
if ( ! $variation || ! $variation->exists() || ( 'yes' === get_option( 'woocommerce_hide_out_of_stock_items' ) && ! $variation->is_in_stock() ) ) {
continue;
}
// Filter 'woocommerce_hide_invisible_variations' to optionally hide invisible variations (disabled variations and variations with empty price).
if ( apply_filters( 'woocommerce_hide_invisible_variations', true, $product->get_id(), $variation ) && ! $variation->variation_is_visible() ) {
continue;
}
$max_qty = 0 < $variation->get_max_purchase_quantity() ? $variation->get_max_purchase_quantity() : $variation->get_stock_quantity();
$term_names = []; // Initializing
// Loop through variation attributes for current varation
foreach ( $variation->get_variation_attributes() as $attribute => $term_slug ) {
// Set the term name in an array
$term_names[] = ucfirst( str_replace( ['-', '_'],[' ', ' '], $term_slug ) );
}
if ( $max_qty > 0 ) {
$excerpt .= sprintf( '<br/>%s: %s %s',
implode(', ', $term_names),
$max_qty,
__('in stock', 'woocommerce')
);
}
}
}
return $excerpt;
}
// Avoid additional content from product short description to be displayed in variation description
add_filter( 'woocommerce_available_variation', 'filter_wc_available_variation_desscription', 10, 3);
function filter_wc_available_variation_desscription( $data, $product, $variation ) {
$max_qty = 0 < $variation->get_max_purchase_quantity() ? $variation->get_max_purchase_quantity() : $variation->get_stock_quantity();
if( $max_qty > 0 )
$data['variation_description'] = get_post_meta( $variation->get_id(), '_variation_description', true );
return $data;
}
This code displays an inventory, but my website language is Persian and the names of the variables are defined in Persian, and this line does not display the variable name code correctly.
How can I fix his language?
And I want to translate the word instock into موجود
And the next point is that I want a button to be displayed on the page first with the title Show product inventory and when the method clicks, the customer will open a pop-up and display the inventory.
Here is the soultion with Persian language:
change
// Loop through variation attributes for current varation
foreach ( $variation->get_variation_attributes() as $attribute => $term_slug ) {
// Set the term name in an array
$term_names[] = ucfirst( str_replace( ['-', '_'],[' ', ' '], $term_slug ) );
}
if ( $max_qty > 0 ) {
$excerpt .= sprintf( '<br/>%s: %s %s',
implode(', ', $term_names),
$max_qty,
__('in stock', 'woocommerce')
);
}
to
// Loop through variation attributes for current varation
foreach ( $variation->get_variation_attributes() as $attribute => $term_name ) {
// Set the term name in an array
$taxonomy = str_replace('attribute_', '', $attribute);
$attribute_name = wc_attribute_label($taxonomy);
$term_name = get_term_by( 'slug', $term_name, $taxonomy)->name;
$term_names[] = $term_name;
}
if ( $max_qty > 0 ) {
$excerpt .= sprintf( '<br/>%s: %s %s',
implode(', ', $term_names),
$max_qty,
__('موجود')
);
}

jquery DataTables erroring on search box

Trying to get DataTables to work with PDO. I found this script online and it works fine, BUT, when I set ATTR_EMULATE_PREPARES to false the search capability does not work and reports back this error.
I cannot view the json response as there is none to view when this error happens, however, in all other cases other than using the search the json is returned properly and it works perfectly fine. Since the error only happens when emulation is set to false I am thinking this has something to do with binding? I cannot figure this one out as I don't see anything wrong that is sticking out at me.
Also, I am not looking to turn on emulation as a solution either. Help would be very appreciated.
the get in firebug:
http://www.example.com/assets/data-tables/test-pdo.php?sEcho=3&iColumns=4&sColumns=&iDisplayStart=0&iDisplayLength=10&mDataProp_0=0&mDataProp_1=1&mDataProp_2=2&mDataProp_3=3&sSearch=d&bRegex=false&sSearch_0=&bRegex_0=false&bSearchable_0=true&sSearch_1=&bRegex_1=false&bSearchable_1=true&sSearch_2=&bRegex_2=false&bSearchable_2=true&sSearch_3=&bRegex_3=false&bSearchable_3=true&iSortCol_0=2&sSortDir_0=asc&iSortingCols=1&bSortable_0=false&bSortable_1=true&bSortable_2=true&bSortable_3=true&_=1388479579319
Error in firebug:
<br />
<b>Fatal error</b>: Uncaught exception 'PDOException' with message 'SQLSTATE[HY093]: Invalid parameter number' in /home/test/public_html/assets/data-tables/test-pdo.php:107
Stack trace:
#0 /home/test/public_html/assets/data-tables/test-pdo.php(107): PDOStatement->execute()
#1 /home/test/public_html/assets/data-tables/test-pdo.php(155): TableData->get('accounts', 'account_id', Array)
#2 {main}
thrown in <b>/home/test/public_html/assets/data-tables/test-pdo.php</b> on line <b>107</b><br />
db connection:
$db = new PDO("mysql:host=$db_host;dbname=$db_database;charset=utf8", $db_user, $db_pass, array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_PERSISTENT => true));
processing:
<?php
/*
* Script: DataTables server-side script for PHP and MySQL
* Copyright: 2012 - John Becker, Beckersoft, Inc.
* Copyright: 2010 - Allan Jardine
* License: GPL v2 or BSD (3-point)
*/
define('INCLUDE_CHECK',true);
// These files can be included only if INCLUDE_CHECK is defined
require '/home/test/public_html/assets/functions/connect.php';
//inject db connection into class
class TableData {
/** #var \PDO */
protected $_db;
public function __construct(\PDO $_db) {
$this->_db = $_db;
}
public function get($table, $index_column, $columns) {
// Paging
$sLimit = "";
if ( isset( $_GET['iDisplayStart'] ) && $_GET['iDisplayLength'] != '-1' ) {
$sLimit = "LIMIT ".intval( $_GET['iDisplayStart'] ).", ".intval( $_GET['iDisplayLength'] );
}
// Ordering
$sOrder = "";
if ( isset( $_GET['iSortCol_0'] ) ) {
$sOrder = "ORDER BY ";
for ( $i=0 ; $i<intval( $_GET['iSortingCols'] ) ; $i++ ) {
if ( $_GET[ 'bSortable_'.intval($_GET['iSortCol_'.$i]) ] == "true" ) {
$sortDir = (strcasecmp($_GET['sSortDir_'.$i], 'ASC') == 0) ? 'ASC' : 'DESC';
$sOrder .= "`".$columns[ intval( $_GET['iSortCol_'.$i] ) ]."` ". $sortDir .", ";
}
}
$sOrder = substr_replace( $sOrder, "", -2 );
if ( $sOrder == "ORDER BY" ) {
$sOrder = "";
}
}
/*
* Filtering
* NOTE this does not match the built-in DataTables filtering which does it
* word by word on any field. It's possible to do here, but concerned about efficiency
* on very large tables, and MySQL's regex functionality is very limited
*/
//need this change to only show correct responses from db
//$test = 100;
//$sWhere = ""; OR $sWhere = "WHERE account_id < ".$test;
$sWhere = "";
if ( isset($_GET['sSearch']) && $_GET['sSearch'] != "" ) {
// changes for correct display from db plus searching
if ($sWhere == ""){
$sWhere = "WHERE (";
}
else {
$sWhere .= " AND (";
}
//$sWhere = "WHERE (";
for ( $i=0 ; $i<count($columns) ; $i++ ) {
if ( isset($_GET['bSearchable_'.$i]) && $_GET['bSearchable_'.$i] == "true" ) {
$sWhere .= "`".$columns[$i]."` LIKE :search OR ";
}
}
$sWhere = substr_replace( $sWhere, "", -3 );
$sWhere .= ')';
}
// Individual column filtering
for ( $i=0 ; $i<count($columns) ; $i++ ) {
if ( isset($_GET['bSearchable_'.$i]) && $_GET['bSearchable_'.$i] == "true" && $_GET['sSearch_'.$i] != '' ) {
if ( $sWhere == "" ) {
$sWhere = "WHERE ";
}
else {
$sWhere .= " AND ";
}
$sWhere .= "`".$columns[$i]."` LIKE :search".$i." ";
}
}
// SQL queries get data to display
$sQuery = "SELECT SQL_CALC_FOUND_ROWS `".str_replace(" , ", " ", implode("`, `", $columns))."` FROM `".$table."` ".$sWhere." ".$sOrder." ".$sLimit;
$statement = $this->_db->prepare($sQuery);
// Bind parameters
if ( isset($_GET['sSearch']) && $_GET['sSearch'] != "" ) {
$statement->bindValue(':search', '%'.$_GET['sSearch'].'%', PDO::PARAM_STR);
}
for ( $i=0 ; $i<count($columns) ; $i++ ) {
if ( isset($_GET['bSearchable_'.$i]) && $_GET['bSearchable_'.$i] == "true" && $_GET['sSearch_'.$i] != '' ) {
$statement->bindValue(':search'.$i, '%'.$_GET['sSearch_'.$i].'%', PDO::PARAM_STR);
}
}
$statement->execute();
$rResult = $statement->fetchAll();
$iFilteredTotal = current($this->_db->query('SELECT FOUND_ROWS()')->fetch());
// Get total number of rows in table
$sQuery = "SELECT COUNT(`".$index_column."`) FROM `".$table."`";
//$sQuery = "SELECT COUNT(`".$index_column."`) FROM `".$table."` WHERE account_id < 100";
$iTotal = current($this->_db->query($sQuery)->fetch());
// Output
$output = array(
"sEcho" => intval($_GET['sEcho']),
"iTotalRecords" => $iTotal,
"iTotalDisplayRecords" => $iFilteredTotal,
"aaData" => array()
);
// Return array of values
foreach($rResult as $aRow) {
$row = array();
for ( $i = 0; $i < count($columns); $i++ ) {
//else if ( $aColumns[$i] != ' ' )
if ( $columns[$i] != ' ' )
{
/* General output */
//if column is empty give it n/a
$row[] = ($aRow[ $columns[$i] ]=="") ? 'n/a' : $aRow[ $columns[$i] ];
}
}
$output['aaData'][] = $row;
}
echo json_encode( $output );
}
}
header('Pragma: no-cache');
header('Cache-Control: no-store, no-cache, must-revalidate');
// Create instance of TableData class
$table_data = new TableData($db);
// Get the data
//$table_data->get('table_name', 'index_column', array('column1', 'column2', 'columnN'));
$table_data->get('accounts', 'account_id', array('account_id', 'account_username', 'account_password', 'account_email'));
?>
I doubt that anyone will be interested, but I finally figured this out. The script was trying to use the same binding, :search, multiple times in the statement.
Even though it will always be the same actual value the error was being thrown as it was the same binding. How I did not see this earlier I do not know, but it is obvious to me now.
//$sWhere .= "`".$columns[$i]."` LIKE :search OR ";
$sWhere .= "`".$columns[$i]."` LIKE :searchm".$i." OR ";
// Bind parameters
//if ( isset($_GET['sSearch']) && $_GET['sSearch'] != "" ) {
// $statement->bindValue(':search', '%'.$_GET['sSearch'].'%', PDO::PARAM_STR);
//}
if ( isset($_GET['sSearch']) && $_GET['sSearch'] != "" ) {
for ( $i=0 ; $i<count($columns) ; $i++ ) {
$statement->bindValue(':searchm'.$i, '%'.$_GET['sSearch'].'%', PDO::PARAM_STR);
}
}

Joomla auto login

How can I auto-login a user in Joomla 1.5. I am using this code:
global $mainframe;
$db =& JFactory::getDBO();
$query = ‘SELECT `id`, `password`, `gid`’. ‘ FROM `#__users`’. ‘ WHERE username=’ . $db->Quote( JRequest::getVar(‘username’, null) ). ‘ AND password=’ . `enter code here` $db->Quote( JRequest::getVar(‘passw’, null) );
$db->setQuery( $query );
$result = $db->loadObject();
if($result) {
JPluginHelper::importPlugin(‘user’);
$response->username = JRequest::getVar(‘username’, null);
$result = $mainframe->triggerEvent(‘onLoginUser’, array((array)$response, $options));
}
$mainframe->redirect(‘XXXXXXXXXXXX’);
Where did I go wrong?
add this top of the code, it will solve the issue
jimport(‘joomla.user.helper’);
// Auto Login customization by Akram abbasi
$mainframe = JFactory::getApplication();
$credentials = array();
$credentials['username'] = $app->input->get('username', '', 'string');
$credentials['password'] = $app->input->get('password', '', 'raw');
$mainframe->login($credentials);
//$mainframe->redirect(JRoute::_('index.php', false));

MODx querying custom db table

See the code below. I'm trying to get some data from a database is modx. The data is there, meaning, when i query the database in phpmyadmin, i get results. I can't figure out why it doesnt work in modx.
$sql = 'SELECT * FROM orders ORDER BY created DESC LIMIT 1';
$stmt = $modx->prepare($sql);
$stmt->execute();
// Put data in array
$order_data = $stmt->fetch(PDO::FETCH_ASSOC);
if ($order_data == '') {
return 'Resultset empty for user '. $user_id.'.<br />'.$sql;
} else {
return 'Data found!';
}
Perhaps try using xPDO:
$sql = 'SELECT * FROM orders ORDER BY created DESC LIMIT 1';
$c = new xPDOCriteria($modx,$sql);
if ($c->stmt && $c->stmt->execute()) {
$order_data = $c->stmt->fetch(PDO::FETCH_ASSOC);
var_dump($order_data);
}
You need to loop through your output, the result will be an array of arrays.
The below example will return the data and present it according to a chunk format
<?php
$sql = "SELECT * FROM `table_name`";
$query = $modx->query($sql);
$rows = array();
if ($query) {
// loop through the result set and inspect one row at a time
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
array_push($rows, $row);
$output .= $modx->getChunk($tpl,$row);
}
}
$output = "<table border=\"1\" cellpadding=\"5\" >
<th>ID</th><th>row1_Head</th><th>row2_Head</th><th>row3_Head</th><th>row4_Head</th><th>row5_Head</th>
$output</table>";
return $output;
This is an example of the chunk:
<tr>
<td>[[+id]]</td> <td>[[+row1]]</td> <td>[[+row2]]</td> <td>[[+row3]]</td> <td>[[+row4]]</td> <td>[[+row5]]</td>
</tr>
Now in a resource call your snippet like
[[!Snippet_name? &tpl=`chunk_name`]]
$sql = 'SELECT * FROM orders ORDER BY created DESC LIMIT 1';
Assume your schema is like
<?xml version="1.0" encoding="UTF-8"?>
<model package="your_package_name" baseClass="xPDOObject" platform="mysql" defaultEngine="MyISAM" version="1.1">
<object class="Orders" table="orders" extends="xPDOSimpleObject">
<field key="order_no" dbtype="varchar" precision="255" phptype="string" null="false" />
<!-- and everything else below -->
</object>
<!-- and everything else below -->
</model>
What you need to do is as simple as this:
$modx->addPackage('your_package_name'); // Add your table schema to MODX object
$orders = $modx->getCollection('Orders'); // class's name, not table's name
$output = '';
if ($orders){
$outputArray = array();
foreach ($orders as $order) {
$orderArray = $order->toArray();
$outputArray[] = $modx->getChunk('your_row_chunk_name', $orderArray);
}
$wrapper = array(
'orders' => #implode("\n", $outputArray);
);
$output = $modx->getChunk('your_wrapper_chunk_name', $wrapper);
}
return $output;

How can I unserialize data from database after it was serialized

try {
if (isset($_SESSION['list']) > 0) {
$test = serialize($_SESSION["list"]);
$sQuery = "INSERT INTO table (id, date) VALUES ('$test', NOW())";
$oStmt = $db->prepare($sQuery);
$oStmt->execute();
}
else {
echo 'No data';
}
}
In my database I see this:
1 a:1:{i:1;s:1:"5";} 2011-12-21
The $_SESSION['list'] stores ID and the QUANTITY.
The data a:1:{i:1;s:1:"5";} is as follow: i=id, s=id:"quantity", I read this as id=1 and the quantity of id=1 is 5, am I correct?
Now I want select the data and unserialize the array.
try {
$sQuery = "SELECT * FROM table";
$oStmt = $db->prepare($sQuery);
$oStmt->execute();
while($aRow = $oStmt->fetchALL(PDO::FETCH_ASSOC)) {
$id = unserialize($aRow['id']);
foreach($id as $id => $quantity) {
echo $id.', ';
}
}
}
catch(PDOException $e) {
$sMsg = '<p>
Regelnummer: '.$e->getLine().'<br />
Bestand: '.$e->getFile().'<br />
Foutmelding: '.$e->getMessage().'
</p>';
trigger_error($sMsg);
}
What am I doing wrong or what can I do so I can select the ID and QUANTITY from database?
The serialization/deserialization part looks fine to me, but the $oStmt->fetchALL( I think should be $oStmt->fetch(, and in foreach($id as $id => $quantity) { use another variable to hold the key instead of id, like foreach($id as $key => $quantity) {.
Also, you don't echo the quantity anywhere. Change echo $id.', '; to echo $key.' '.$quantity; or something and tell us what the output is so we can help further.