jquery DataTables erroring on search box - pdo

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

Related

I can't access admin panel of my script : Invalid query You have an error in your SQL syntax

I have an error message when i try to access my script (php):
Invalid query: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 's marketing advertising'' at line 1
This is a admin php file contain mysql query
<?php
$stt_query = $ocdb->get_rows("SELECT * FROM ".$config->prefix."search order by id desc limit 13" );
if (count( $stt_query ) > 0) {
foreach ($stt_query as $row) :
?>
<li><?php echo $row['title'];?></li>
<?php
endforeach;
}
?>
the php query page:
<?php class OCDB { var $server = ""; var $port = ""; var $db = ""; var $user = ""; var $password = ""; var $prefix = ""; var $insert_id; var $link; function __construct($_server, $_port, $_db, $_user, $_password, $_prefix) { $this->server = $_server; $this->port = $_port; $this->db = $_db; $this->user = $_user; $this->password = $_password; $this->prefix = $_prefix; $host = $this->server; if (defined('DB_HOST_PORT') && !empty($this->port)) $host .= ':'.$this->port; $this->link = mysqli_connect($host, $this->user, $this->password) or die("Could not connect: " . mysqli_connect_error()); mysqli_select_db($this->link, $this->db) or die ('Can not use database : ' . mysqli_error($this->link)); mysqli_query($this->link, 'SET NAMES utf8'); } function get_row($_sql) { //$res = $this->link->query($_sql); //if ($this->link->error) { //try { //throw new Exception("MySQL error $mysqli->error <br> Query:<br> $query", $this->link->errno); //} catch(Exception $e ) { //echo "Error No: ".$e->getCode(). " - ". $e->getMessage() . "<br >"; //echo nl2br($e->getTraceAsString()); //} //} $result = mysqli_query($this->link, $_sql) or die("Invalid query: " . mysqli_error($this->link)); $row = mysqli_fetch_array($result, MYSQL_ASSOC); mysqli_free_result($result); return $row; mysqli_close($this->link); } function get_rows($_sql) { $rows = array(); $result = mysqli_query($this->link, $_sql) or die("Invalid query: " . mysqli_error($this->link)); while ($row = mysqli_fetch_array($result, MYSQL_ASSOC)) { $rows[] = $row; } mysqli_free_result($result); return $rows; } function get_var($_sql) { $result = mysqli_query($this->link, $_sql) or die("Invalid query: " . mysqli_error($this->link)); $row = mysqli_fetch_array($result, MYSQL_NUM); mysqli_free_result($result); if ($row && is_array($row)) return $row[0]; return false; } function query($_sql) { $result = mysqli_query($this->link, $_sql) or die("Invalid query: " . mysqli_error($this->link)); $this->insert_id = mysqli_insert_id($this->link); return $result; } function escape_string($_string) { return mysqli_real_escape_string($this->link, $_string); } } ?>
Please can you help me i can't access admin panel because of this error.
Thanks

Notice: Undefined index: sEcho datatable

I'm having trouble fixing the error Notice: Undefined index: sEcho, I'm using server process script datatable. enter image description here
This is my code of the server_process I'm using:
<?php
/**
* Script: DataTables server-side script for PHP 5.2+ and MySQL 4.1+
* Notes: Based on a script by Allan Jardine that used the old PHP mysql_* functions.
* Rewritten to use the newer object oriented mysqli extension.
* Copyright: 2010 - Allan Jardine (original script)
* 2012 - Kari Söderholm, aka Haprog (updates)
* License: GPL v2 or BSD (3-point)
*/
mb_internal_encoding('UTF-8');
/**
* Array of database columns which should be read and sent back to DataTables. Use a space where
* you want to insert a non-database field (for example a counter or static image)
*/
$aColumns = array( 'id_clien', 'nom_comp_clien', 'exten', 'correo', 'nombre_ofi', 'no_piso', 'id_ofi_c' );
// Indexed column (used for fast and accurate table cardinality)
$sIndexColumn = 'id_clien';
// DB table to use
$sTable = array('clientes' , 'oficinas');
// Database connection information
$gaSql['user'] = 'root';
$gaSql['password'] = '';
$gaSql['db'] = 'sistemacaem';
$gaSql['server'] = 'localhost';
$gaSql['port'] = 3306; // 3306 is the default MySQL port
// Input method (use $_GET, $_POST or $_REQUEST)
$input =& $_GET;
/** * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* If you just want to use the basic configuration for DataTables with PHP server-side, there is
* no need to edit below this line
*/
/**
* Character set to use for the MySQL connection.
* MySQL will return all strings in this charset to PHP (if the data is stored correctly in the database).
*/
$gaSql['charset'] = 'utf8';
/**
* MySQL connection
*/
$db = new mysqli($gaSql['server'], $gaSql['user'], $gaSql['password'], $gaSql['db'], $gaSql['port']);
if (mysqli_connect_error()) {
die( 'Error connecting to MySQL server (' . mysqli_connect_errno() .') '. mysqli_connect_error() );
}
if (!$db->set_charset($gaSql['charset'])) {
die( 'Error loading character set "'.$gaSql['charset'].'": '.$db->error );
}
/**
* Paging
*/
$sLimit = "";
if ( isset( $input['iDisplayStart'] ) && $input['iDisplayLength'] != '-1' ) {
$sLimit = " LIMIT ".intval( $input['iDisplayStart'] ).", ".intval( $input['iDisplayLength'] );
}
/**
* Ordering
*/
$aOrderingRules = array();
if ( isset( $input['iSortCol_0'] ) ) {
$iSortingCols = intval( $input['iSortingCols'] );
for ( $i=0 ; $i<$iSortingCols ; $i++ ) {
if ( $input[ 'bSortable_'.intval($input['iSortCol_'.$i]) ] == 'true' ) {
$aOrderingRules[] =
"`".$aColumns[ intval( $input['iSortCol_'.$i] ) ]."` "
.($input['sSortDir_'.$i]==='asc' ? 'asc' : 'desc');
}
}
}
if (!empty($aOrderingRules)) {
$sOrder = " ORDER BY ".implode(", ", $aOrderingRules);
} else {
$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
*/
$iColumnCount = count($aColumns);
if ( isset($input['sSearch']) && $input['sSearch'] != "" ) {
$aFilteringRules = array();
for ( $i=0 ; $i<$iColumnCount ; $i++ ) {
if ( isset($input['bSearchable_'.$i]) && $input['bSearchable_'.$i] == 'true' ) {
$aFilteringRules[] = "`".$aColumns[$i]."` LIKE '%".$db->real_escape_string( $input['sSearch'] )."%'";
}
}
if (!empty($aFilteringRules)) {
$aFilteringRules = array('('.implode(" OR ", $aFilteringRules).')');
}
}
// Individual column filtering
for ( $i=0 ; $i<$iColumnCount ; $i++ ) {
if ( isset($input['bSearchable_'.$i]) && $input['bSearchable_'.$i] == 'true' && $input['sSearch_'.$i] != '' ) {
$aFilteringRules[] = "`".$aColumns[$i]."` LIKE '%".$db->real_escape_string($input['sSearch_'.$i])."%'";
}
}
if (!empty($aFilteringRules)) {
$sWhere = " WHERE id_ofi_c = id_ofi ".implode(" AND ", $aFilteringRules);
} else {
$sWhere = "WHERE id_ofi_c = id_ofi ";
}
/**
* SQL queries
* Get data to display
*/
$aQueryColumns = array();
foreach ($aColumns as $col) {
if ($col != ' ') {
$aQueryColumns[] = $col;
}
}
$sQuery = "
SELECT SQL_CALC_FOUND_ROWS `".implode("`, `", $aQueryColumns)."`
FROM `".implode("`, `", $sTable)."`".$sWhere.$sOrder.$sLimit;
$rResult = $db->query( $sQuery ) or die($db->error);
// Data set length after filtering
$sQuery = "SELECT FOUND_ROWS()";
$rResultFilterTotal = $db->query( $sQuery ) or die($db->error);
list($iFilteredTotal) = $rResultFilterTotal->fetch_row();
// Total data set length
$sQuery = "SELECT COUNT(`".$sIndexColumn."`) FROM `".implode("`, `",$sTable)."`";
$rResultTotal = $db->query( $sQuery ) or die($db->error);
list($iTotal) = $rResultTotal->fetch_row();
/**
* Output
*/
$output = array(
"sEcho" => intval($input['sEcho']),
"iTotalRecords" => $iTotal,
"iTotalDisplayRecords" => $iFilteredTotal,
"aaData" => array(),
);
while ( $aRow = $rResult->fetch_assoc() ) {
$row = array();
// for ( $i=0 ; $i<$iColumnCount ; $i++ ) {
// if ( $aColumns[$i] == 'version' ) {
// // Special output formatting for 'version' column
// $row[] = ($aRow[ $aColumns[$i] ]=='0') ? '-' : $aRow[ $aColumns[$i] ];
// } elseif ( $aColumns[$i] != ' ' ) {
// // General output
// $row[] = $aRow[ $aColumns[$i] ];
// }
// }
$row[] = $aRow[ $aColumns[0] ];
$row[] = $aRow[ $aColumns[1] ];
$row[] = $aRow[ $aColumns[2] ];
$row[] = $aRow[ $aColumns[3] ];
$row[] = $aRow[ $aColumns[4] ];
$row[] = $aRow[ $aColumns[5] ];
$row[] = $aRow[ $aColumns[6] ];
$output['aaData'][] = $row;
}
echo json_encode( $output );
?>
I'll be very grateful if somebody could help me out.

CDbCriteria throwing column name is ambigous

I have the following method in a controller of my Yii app.
public function actionManage($typeid=0, $locationid=0, $page=1, $rows=12, $sidx='date_input', $sord='desc', $kategori='')
{
if (Yii::app()->request->isAjaxRequest) {
// Jika dilakukan operasi 'edit' pada row
if (isset($_REQUEST['oper']))
{
$oper = $_REQUEST['oper'];
$id = $_REQUEST['id'];
if ($oper == 'edit')
{
$value = $_REQUEST['value'];
$record = InputData::model()->findByPk($id);
$record->value = $value;
$record->update();
}
if($oper == 'delete'){
$model = InputData::model()->findByPk($id);
$model->delete();
}
}
// inisialisasi criteria query
$criteria = new CDbCriteria();
$criteria->order = "$sidx $sord";
// filter lokasi
if (is_numeric($locationid) && $locationid !== 0)
{
$criteria->with = array('data'=>array(
'condition'=>'data.locationid=:locationid',
'params'=>array(':locationid'=>$locationid)
));
} else {
if (is_numeric($typeid) && $typeid !== 0)
{
$criteria->with = array('data.location'=>array(
'with'=>array(
'type'=>array(
'condition'=>'type.typeid=:typeid',
'params'=>array(':typeid'=>$typeid)
)
)
));
} else {
$criteria->with = array('data.location'=>array(
'with'=>array(
'type'=>array(
'condition'=>'type.type_desc=:type_desc',
'params'=>array(':type_desc'=>$kategori)
)
)
));
}
}
// filter range tanggal
if (isset($_REQUEST['startdate'], $_REQUEST['enddate']))
{
$startdate = $_REQUEST['startdate'];
$enddate = $_REQUEST['enddate'];
$criteria->condition = 'date_input <= :enddate AND date_input >= :startdate';
$criteria->params = array(':startdate'=>$startdate, ':enddate'=>$enddate);
}
if(isset($_REQUEST['dataid'])){
$dataid = $_REQUEST['dataid'];
$criteria->addCondition("dataid = $dataid");
}
$dataProvider = new CActiveDataProvider('InputData', array(
'criteria'=>$criteria,
'pagination'=>array(
'currentPage'=>$page-1,
'pageSize'=>$rows
)
));
$count = $dataProvider->totalItemCount;
$total_pages = $count > 0 ? ceil($count/$rows) : 0;
if ($page > $total_pages) $page=$total_pages;
// generate response untuk jqgrid
$response = new stdClass();
$response->page = $page;
$response->total = $total_pages;
$response->records = $count;
foreach($dataProvider->getData() as $row)
{
$response->rows[] = array(
'id'=>$row->inputdataid,
'cell'=>array(
$row->inputdataid,
$row->date_input,
$row->time_input,
$row->data->location->location_name,
$row->data->data_name,
$row->data->variable->var_name,
round($row->value, 3),
$row->data->variable->unit->uom_name,
($row->inputOfficer !== NULL ? $row->inputOfficer->officer_name:''),
'<i class="fa fa-pencil-square-o"></i> Edit <i class="fa fa-trash-o"></i> Delete'
)
);
}
echo json_encode($response);
} else {
$url = $this->createUrl("dataAir/manage");
$delurl = $this->createUrl("dataAir/deleteRow");
$startdate = '2013-01-01';
$enddate = date_format(new DateTime(), 'Y-m-d');
$this->render('jqgrid', array(
'kategori'=>$kategori,
'url'=>$url,
'delurl'=>$delurl,
'startdate'=>$startdate,
'enddate'=>$enddate
));
}
}
this line causing the problem
if(isset($_REQUEST['dataid'])){
$dataid = $_REQUEST['dataid'];
$criteria->addCondition("dataid = $dataid");
}
when, I remove those lines the method work just fine. what could be the problem causing ambigous colum name? here is the error log
SELECT COUNT(DISTINCT "t"."inputdataid") FROM "app_inputdata" "t" LEFT OUTER JOIN "app_ref_periodicdata" "data" ON ("t"."dataid"="data"."dataid") WHERE ((date_input <= :enddate AND date_input >= :startdate) AND (dataid = 7)) AND (data.locationid=:locationid). Bound with :startdate='2013-01-01', :enddate='2015-02-02', :locationid='6'
You need to add the table alias t to your condition:
$criteria->addCondition("t.dataid = $dataid");
Also, since $dataid is being obtained from a $_REQUEST it is best to pass it as a parameter. This can be done in two ways:
$criteria->addCondition("t.dataid = :dataid", [":dataid" => $dataid]);
$criteria->compare("t.dataid", $dataid);
you have used table aliases,
'with'=>array(
'type'=>array(
'condition'=>'type.type_desc=:type_desc', <<- I mean here you have used alias : type
'params'=>array(':type_desc'=>$kategori)
)
you just have to remember that the main model that you are working with, will always need alias t to unambigufy! (not sure if that is an actual word :D )

Magento API, Return Orders with NULL values

Using the magento api version 1 and soap.
Need to return all orders with 'coupon_code'=> NULL
The call I'm attempting:
$order_listAR = $proxy->call($sessionId, 'sales_order.list', array(array('coupon_code'=>array('null'=>'null'))));
The ouput I want returned is this:
array(237) {
["state"]=>
string(8) "complete"
["status"]=>
string(8) "complete"
["coupon_code"]=> NULL
So far this seems to work properly, but I'm not sure if ('null'=>'null') is the proper way to find NULL values in the array. Can someone explain why this works, and, or if this is the correct syntax? I don't have any margin for error on this.
Yes, the syntax you use is correct to filter against null.
array(
'coupon_code' => array(
'null' => 'this_value_doesnt_matter'
)
)
Magento maps* the API method sales_order.list to Mage_Sales_Model_Order_Api::items().
public function items($filters = null)
{
:
$collection = Mage::getModel("sales/order")->getCollection()
:
if (is_array($filters)) {
try {
foreach ($filters as $field => $value) {
if (isset($this->_attributesMap['order'][$field])) {
$field = $this->_attributesMap['order'][$field];
}
$collection->addFieldToFilter($field, $value);
}
} catch (Mage_Core_Exception $e) {
$this->_fault('filters_invalid', $e->getMessage());
}
}
:
}
The items() method uses a Mage_Sales_Model_Resource_Order_Collection to fetch the orders for the API call. That collection is based on Varien_Data_Collection_Db, so
$collection->addFieldToFilter($field, $value)
from above essentially does call
Varien_Data_Collection_Db::addFieldToFilter()
If you follow the latter, you'll hit Varien_Db_Adapter_Pdo_Mysql::prepareSqlCondition() in the end, params being
$fieldName = 'coupon_code'
$condition = array('null' => 'null')
Excerpt of that method:
public function prepareSqlCondition($fieldName, $condition)
{
$conditionKeyMap = array(
'eq' => "{{fieldName}} = ?",
:
'notnull' => "{{fieldName}} IS NOT NULL",
'null' => "{{fieldName}} IS NULL",
:
'sneq' => null
);
:
$query = '';
if (is_array($condition)) {
:
$key = key(array_intersect_key($condition, $conditionKeyMap));
if (isset($condition['from']) || isset($condition['to'])) {
:
} elseif (array_key_exists($key, $conditionKeyMap)) {
$value = $condition[$key];
if (($key == 'seq') || ($key == 'sneq')) {
:
}
$query = $this->_prepareQuotedSqlCondition($conditionKeyMap[$key], $value, $fieldName);
} else {
:
}
}
:
}
In your case _prepareQuotedSqlCondition() will be called with
$text = '{{fieldName}} IS NULL'
$value = 'null'
$fieldName = 'coupon_code'
which will result in $query = 'coupon_code IS NULL'.
If you take a closer look at the conversion method
protected function _prepareQuotedSqlCondition($text, $value, $fieldName)
{
$sql = $this->quoteInto($text, $value);
$sql = str_replace('{{fieldName}}', $fieldName, $sql);
return $sql;
}
you'll also see, why the value of the 'null' => 'null' key/value pair does not matter at all. That's because $text will be '{{fieldName}} IS NULL', i.e. not containing any binding ?.
Hence, there's nothing to replace for _quoteInto()^^
* see app/code/core/Mage/Sales/etc/api.xml

php - how do I use a form to display data with multiple where conditions?

I created a database for a volunteers list. Then a form to pull out the personal info for volunteers who signed up to volunteer for particular tasks. I'm a beginner with php, and I have looked all over for an answer and tried multiple ways of doing it, but alas, no luck.
Here is the critical code I am currently struggling with:
if(isset($_POST['planning']) && $_POST['planning'] == '1')
{ $result1 = mysql_query("SELECT * FROM volunteers WHERE planning = '1'");}
if(isset($_POST['signatures']) && $_POST['signatures'] == '1')
{ $result2 = mysql_query("SELECT * FROM volunteers WHERE signatures = '1'");
$newresult1 = array_merge($result1, $result2);}
if(isset($_POST['canvassing']) && $_POST['canvassing'] == '1')
{ $result3 = mysql_query("SELECT * FROM volunteers WHERE canvassing = '1'");
$newresult2 = array_merge($newresult1, $result3);}
if(isset($_POST['phone_bank']) && $_POST['phone_bank'] == '1')
{ $result4 = mysql_query("SELECT * FROM volunteers WHERE phone_bank = '1'");
$newresult3 = array_merge($newresult2, $result4);}
if(isset($_POST['media']) && $_POST['media'] == '1')
{ $result5 = mysql_query("SELECT * FROM volunteers WHERE media = '1'"); $newresult4 =
array_merge($newresult3, $result5);}
if(isset($_POST['press_releases']) && $_POST['press_releases'] == '1')
{ $result6 = mysql_query("SELECT * FROM volunteers WHERE press_releases = '1'");
$newresult5 = array_merge($newresult4, $result6);}
if(isset($_POST['volunteer_coordinator']) && $_POST['volunteer_coordinator'] == '1')
{ $result7 = mysql_query("SELECT * FROM volunteers WHERE volunteer_coordinator =
'1'");
$newresult6 = array_merge($newresult5, $result7);}
if(isset($_POST['speaker']) && $_POST['speaker'] == '1')
{ $result8 = mysql_query("SELECT * FROM volunteers WHERE speaker = '1'"); $newresult7
= array_merge($newresult6, $result8);}
if(isset($_POST['house_parties']) && $_POST['house_parties'] == '1')
{ $result9 = mysql_query("SELECT * FROM volunteers WHERE house_parties = '1'");
$newresult8 = array_merge($newresult7, $result9);}
if(isset($_POST['web_page']) && $_POST['web_page'] == '1')
{ $result10 = mysql_query("SELECT * FROM volunteers WHERE web_page = '1'");
$newresult9
= array_merge($newresult8, $result10);}
if(isset($_POST['other']) && $_POST['other'] == '1')
{ $result11 = mysql_query("SELECT * FROM volunteers WHERE other = '1'"); $newresult10
= array_merge($newresult9, $result11);}
$newresult10 = array_unique($newresult10);
while($row = mysql_fetch_array($newresult10)) {
echo $row['first_name'] . " " . $row['last_name'];
echo " ";
echo $row['email'];
echo " ";
echo $row['phone'];
echo "<br />";
I much appreciated any suggestions.
You could write it so that it's more like this
[EDIT]-------- I think this is what your looking for
$postVars = array(
"canvassing"=>"1",
"other"=>"1"
//and you would go on post name valid post value
);
//start the query
$query="SELECT * FROM volunteers WHERE ";
//loop thru the posibable post vars and check and add to the query
$andcount=0;
foreach($postVars as $name=>$value){
if(isset($_POST[$name]) && $_POST[$name] == $value){
if($andcount>0)$query.=" AND ";
$query.=" ".$name."= '".mysql_real_escape_string($value)."'";
$andcount++;
}
}
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
echo $row['first_name'] . " " . $row['last_name'];
echo " ";
echo $row['email'];
echo " ";
echo $row['phone'];
echo "<br />";
}