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
this is the example of signup page. the error is"Notice: Array to string conversion in
C:\xampp\htdocs\sample\signup.php on line 96" what are the possible solutions.
here is the code........
<?php
$con = mysqli_connect('localhost','root') or die(mysqli_error());
mysqli_select_db($con,'kms') or die (mysqli_error());
if (isset($_POST['techno']) && isset($_FILES['profile_picture']))
{
$firstname = $_POST['firstname'];
$middlename = $_POST['middlename'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$password = $_POST['password'];
$psw_repeat = $_POST['psw_repeat'];
$dob = $_POST['dob'];
$gender = $_POST['gender'];
$occupation = $_POST['occupation'];
$address = $_POST['address'];
$about = $_POST['about'];
$phonenumber = $_POST['phonenumber'];
$profile_picture = $_FILES['profile_picture'];
$q = "INSERT INTO user (firstname,middlename,lastname,email,password,dob,gender,occupation,address,about,phonenumber,profile_picture) values ('$firstname','$middlename','$lastname','$email','$password',$dob,'$gender','$occupation','$address','$about',$phonenumber,'$profile_picture')";
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["profile_picture"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["profile_picture"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["profile_picture"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["profile_picture"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["profile_picture"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
if($psw_repeat != $password)
{
echo("Password does not match");
}
mysqli_query($con,$q) or die(mysqli_error($con));
mysqli_close($con);
}
?>
in line number 96...the code is for inserting data into database...
i have googled this error....ut there is no solution
how to Validation IRAN Code Meli in Ajax ActiveForm Yii2
Correct:
2595722751
not Correct:
2595722752
Step1: in view
<?php $form = ActiveForm::begin(['enableAjaxValidation' => true]); ?>
Step2: function in model
public function checkCodeMeli()
{
$code_melli = $this->code_meli;
if (!preg_match('/^[0-9]{10}$/', $code_melli)) {
$this->addError('code_meli', 'کد ملی باید 10 رقم باشد');
}
for ($i = 0; $i < 10; $i++) {
if (preg_match('/^' . $i . '{10}$/', $code_melli)) {
$this->addError('code_meli', 'کد ملی صحیح وارد نشده است');
}
}
for ($i = 0, $sum = 0; $i < 9; $i++) {
$sum += ((10 - $i) * intval(substr($code_melli, $i, 1)));
}
$ret = $sum % 11;
$parity = intval(substr($code_melli, 9, 1));
if (($ret < 2 && $ret == $parity) || ($ret >= 2 && $ret == 11 - $parity)) {
return true;
}
else {
$this->addError('code_meli', 'کد ملی صحیح وارد نشده است');
}
}
Step3: rule in Model
['code_meli', 'checkCodeMeli'],
Step4: in controller
$model = new Model();
if(Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
My Dear Buddies,
I need your help to make captcha case sensitive phpfox,
i want to make captcha not case sensitive in my phpfox site. please help me.
i can not find code for change case sensitivity in phpfox captcha module, and there is no any settings in phpfox backend for that so ple help me.
here is code of
captcha.class.php
<?php
/**
* [PHPFOX_HEADER]
*/
defined('PHPFOX') or exit('NO DICE!');
/**
*
*
* #copyright [PHPFOX_COPYRIGHT]
* #author Raymond Benc
* #package Module_Captcha
* #version $Id: captcha.class.php 6005 2013-06-06 14:12:12Z Raymond_Benc $
*/
class Captcha_Service_Captcha extends Phpfox_Service
{
private $_oSession;
/**
* Class constructor
*/
public function __construct()
{
$this->_oSession = Phpfox::getService('log.session');
}
public function checkHash($sCode = null)
{
if (Phpfox::getParam('captcha.recaptcha'))
{
require_once(PHPFOX_DIR_LIB . 'recaptcha' . PHPFOX_DS . 'recaptchalib.php');
if (isset($_POST["recaptcha_response_field"]))
{
$oResp = recaptcha_check_answer(Phpfox::getParam('captcha.recaptcha_private_key'), $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]);
if ($oResp->is_valid){
return true;
}else{
return false;
}
}
return false;
}
if (Phpfox::getParam('core.store_only_users_in_session'))
{
$oSession = Phpfox::getLib('session');
$sSessionHash = $oSession->get('sessionhash');
$aRow = $this->database()->select('*')
->from(Phpfox::getT('log_session'))
->where('session_hash = \'' . $this->database()->escape($sSessionHash) . '\'')
->execute('getSlaveRow');
if (isset($aRow['session_hash']) && $this->_getHash(strtolower($sCode), $aRow['session_hash']) == $aRow['captcha_hash'])
{
return true;
}
}
else
{
if ($this->_getHash(strtolower($sCode), $this->_oSession->getSessionId()) == $this->_oSession->get('captcha_hash'))
{
return true;
}
}
return false;
}
public function setHash($sCode)
{
if (Phpfox::getParam('core.store_only_users_in_session'))
{
$oRequest = Phpfox_Request::instance();
$oSession = Phpfox::getLib('session');
$sSessionHash = $oSession->get('sessionhash');
$bCreate = true;
if (!empty($sSessionHash))
{
$bCreate = false;
$aRow = $this->database()->select('*')
->from(Phpfox::getT('log_session'))
->where('session_hash = \'' . $this->database()->escape($sSessionHash) . '\'')
->execute('getSlaveRow');
if (isset($aRow['session_hash']))
{
$this->database()->update(Phpfox::getT('log_session'), array('captcha_hash' => $this->_getHash($sCode, $sSessionHash)), "session_hash = '" . $sSessionHash . "'");
}
else
{
$bCreate = true;
}
}
if ($bCreate)
{
$sSessionHash = $oRequest->getSessionHash();
$this->database()->insert(Phpfox::getT('log_session'), array(
'session_hash' => $sSessionHash,
'id_hash' => $oRequest->getIdHash(),
'captcha_hash' => $this->_getHash($sCode, $sSessionHash),
'user_id' => Phpfox::getUserId(),
'last_activity' => PHPFOX_TIME,
'location' => '',
'is_forum' => '0',
'forum_id' => 0,
'im_hide' => 0,
'ip_address' => '',
'user_agent' => ''
)
);
$oSession->set('sessionhash', $sSessionHash);
}
}
else
{
$iId = $this->_oSession->getSessionId();
$this->database()->update(Phpfox::getT('log_session'), array('captcha_hash' => $this->_getHash($sCode, $iId)), "session_hash = '" . $iId . "'");
}
}
public function displayCaptcha($sText)
{
((Phpfox::getParam('captcha.captcha_use_font') && function_exists('imagettftext')) ? $this->_writeFromFont($sText) : $this->_writeFromString($sText));
ob_clean();
header("X-Content-Encoded-By: phpFox " . PhpFox::getVersion());
header("Pragma: no-cache");
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Content-Type: image/jpeg');
imagejpeg($this->_hImg);
imagedestroy($this->_hImg);
}
public function generateCode($sCharacters)
{
$sPossible = Phpfox::getParam('captcha.captcha_code');
$sCode = '';
$i = 0;
while ($i < $sCharacters)
{
$sCode .= substr($sPossible, mt_rand(0, strlen($sPossible)-1), 1);
$i++;
}
return strtolower($sCode);
}
/**
* If a call is made to an unknown method attempt to connect
* it to a specific plug-in with the same name thus allowing
* plug-in developers the ability to extend classes.
*
* #param string $sMethod is the name of the method
* #param array $aArguments is the array of arguments of being passed
*/
public function __call($sMethod, $aArguments)
{
/**
* Check if such a plug-in exists and if it does call it.
*/
if ($sPlugin = Phpfox_Plugin::get('captcha.service_captcha__call'))
{
return eval($sPlugin);
}
/**
* No method or plug-in found we must throw a error.
*/
Phpfox_Error::trigger('Call to undefined method ' . __CLASS__ . '::' . $sMethod . '()', E_USER_ERROR);
}
private function _getHash($sCode, $sSalt)
{
return md5(md5($sCode) . $sSalt);
}
private function _writeFromFont($sText)
{
$iString = strlen($sText);
$iWidth = (($iString + 5) * 10 * 2);
$iHeight = 45;
$iTextSize = 20;
$sFont = Phpfox::getParam('core.dir_static') . 'image/font/' . Phpfox::getParam('captcha.captcha_font');
if (!file_exists($sFont))
{
return $this->_writeFromString($sText);
}
$this->_imageCreate($iWidth, $iHeight);
$nBgColor = imageColorAllocate($this->_hImg, 255, 255, 255);
$nTxtColor = imageColorAllocate($this->_hImg, 0, 0, 0);
if (!($aBox = #imagettfbbox($iTextSize, 0, $sFont, $sText)))
{
return $this->_writeFromString($sText);
}
//Find out the width and height of the text box
$iTextW = $aBox[2] - $aBox[0];
$iTextH = $aBox[5] - $aBox[3];
if (function_exists('imagefilledellipse'))
{
$nNoiseColor = imagecolorallocate($this->_hImg, 207, 181, 181);
for ($i = 0; $i < ($iWidth*$iHeight) / 3; $i++)
{
imagefilledellipse($this->_hImg, mt_rand(0, $iWidth), mt_rand(0, $iHeight), 1, 1, $nNoiseColor);
}
}
$iImageLineColor = imagecolorallocate($this->_hImg, 207, 181, 181);
for ($i = 0; $i < ($iWidth*$iHeight) / 150; $i++)
{
imageline($this->_hImg, mt_rand(0, $iWidth), mt_rand(0, $iHeight), mt_rand(0, $iWidth), mt_rand(0, $iHeight), $iImageLineColor);
}
// Calculate the positions
$positionLeft = (($iWidth - $iTextW) / 2) - (20 + $iString);
$positionTop = (($iHeight - $iTextH) / 2);
for ($i = 0; $i < $iString; $i++)
{
if (!#imagettftext($this->_hImg, $iTextSize, 0, $positionLeft, 30, $nTxtColor, $sFont, $sText[$i]))
{
return $this->_writeFromString($sText);
}
$positionLeft += 20;
}
}
private function _writeFromString($sText)
{
$iString = strlen($sText);
$iWidth = (($iString + 5) * 6.4 * 2);
$iHeight = 40;
$this->_imageCreate($iWidth, $iHeight);
$nBgColor = imageColorAllocate($this->_hImg, 255, 255, 255);
$nTxtColor = imageColorAllocate($this->_hImg, 0, 0, 0);
$positionLeft = 20;
for ($i = 0; $i < $iString; $i++)
{
imagestring($this->_hImg, 5, $positionLeft, 12, $sText[$i], $nTxtColor);
$positionLeft += 15;
}
}
private function _imageCreate($iWidth, $iHeight)
{
$this->_hImg = imageCreate($iWidth, $iHeight);
}
}
?>
You need to remove all the code that use strtolower().
Here the fixed code:
<?php
/**
* [PHPFOX_HEADER]
*/
defined('PHPFOX') or exit('NO DICE!');
/**
*
*
* #copyright [PHPFOX_COPYRIGHT]
* #author Raymond Benc
* #package Module_Captcha
* #version $Id: captcha.class.php 6005 2013-06-06 14:12:12Z Raymond_Benc $
*/
class Captcha_Service_Captcha extends Phpfox_Service
{
private $_oSession;
/**
* Class constructor
*/
public function __construct()
{
$this->_oSession = Phpfox::getService('log.session');
}
public function checkHash($sCode = null)
{
if (Phpfox::getParam('captcha.recaptcha'))
{
require_once(PHPFOX_DIR_LIB . 'recaptcha' . PHPFOX_DS . 'recaptchalib.php');
if (isset($_POST["recaptcha_response_field"]))
{
$oResp = recaptcha_check_answer(Phpfox::getParam('captcha.recaptcha_private_key'), $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]);
if ($oResp->is_valid){
return true;
}else{
return false;
}
}
return false;
}
if (Phpfox::getParam('core.store_only_users_in_session'))
{
$oSession = Phpfox::getLib('session');
$sSessionHash = $oSession->get('sessionhash');
$aRow = $this->database()->select('*')
->from(Phpfox::getT('log_session'))
->where('session_hash = \'' . $this->database()->escape($sSessionHash) . '\'')
->execute('getSlaveRow');
if (isset($aRow['session_hash']) && $this->_getHash($sCode, $aRow['session_hash']) == $aRow['captcha_hash'])
{
return true;
}
}
else
{
if ($this->_getHash($sCode, $this->_oSession->getSessionId()) == $this->_oSession->get('captcha_hash'))
{
return true;
}
}
return false;
}
public function setHash($sCode)
{
if (Phpfox::getParam('core.store_only_users_in_session'))
{
$oRequest = Phpfox_Request::instance();
$oSession = Phpfox::getLib('session');
$sSessionHash = $oSession->get('sessionhash');
$bCreate = true;
if (!empty($sSessionHash))
{
$bCreate = false;
$aRow = $this->database()->select('*')
->from(Phpfox::getT('log_session'))
->where('session_hash = \'' . $this->database()->escape($sSessionHash) . '\'')
->execute('getSlaveRow');
if (isset($aRow['session_hash']))
{
$this->database()->update(Phpfox::getT('log_session'), array('captcha_hash' => $this->_getHash($sCode, $sSessionHash)), "session_hash = '" . $sSessionHash . "'");
}
else
{
$bCreate = true;
}
}
if ($bCreate)
{
$sSessionHash = $oRequest->getSessionHash();
$this->database()->insert(Phpfox::getT('log_session'), array(
'session_hash' => $sSessionHash,
'id_hash' => $oRequest->getIdHash(),
'captcha_hash' => $this->_getHash($sCode, $sSessionHash),
'user_id' => Phpfox::getUserId(),
'last_activity' => PHPFOX_TIME,
'location' => '',
'is_forum' => '0',
'forum_id' => 0,
'im_hide' => 0,
'ip_address' => '',
'user_agent' => ''
)
);
$oSession->set('sessionhash', $sSessionHash);
}
}
else
{
$iId = $this->_oSession->getSessionId();
$this->database()->update(Phpfox::getT('log_session'), array('captcha_hash' => $this->_getHash($sCode, $iId)), "session_hash = '" . $iId . "'");
}
}
public function displayCaptcha($sText)
{
((Phpfox::getParam('captcha.captcha_use_font') && function_exists('imagettftext')) ? $this->_writeFromFont($sText) : $this->_writeFromString($sText));
ob_clean();
header("X-Content-Encoded-By: phpFox " . PhpFox::getVersion());
header("Pragma: no-cache");
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Content-Type: image/jpeg');
imagejpeg($this->_hImg);
imagedestroy($this->_hImg);
}
public function generateCode($sCharacters)
{
$sPossible = Phpfox::getParam('captcha.captcha_code');
$sCode = '';
$i = 0;
while ($i < $sCharacters)
{
$sCode .= substr($sPossible, mt_rand(0, strlen($sPossible)-1), 1);
$i++;
}
return $sCode;
}
/**
* If a call is made to an unknown method attempt to connect
* it to a specific plug-in with the same name thus allowing
* plug-in developers the ability to extend classes.
*
* #param string $sMethod is the name of the method
* #param array $aArguments is the array of arguments of being passed
*/
public function __call($sMethod, $aArguments)
{
/**
* Check if such a plug-in exists and if it does call it.
*/
if ($sPlugin = Phpfox_Plugin::get('captcha.service_captcha__call'))
{
return eval($sPlugin);
}
/**
* No method or plug-in found we must throw a error.
*/
Phpfox_Error::trigger('Call to undefined method ' . __CLASS__ . '::' . $sMethod . '()', E_USER_ERROR);
}
private function _getHash($sCode, $sSalt)
{
return md5(md5($sCode) . $sSalt);
}
private function _writeFromFont($sText)
{
$iString = strlen($sText);
$iWidth = (($iString + 5) * 10 * 2);
$iHeight = 45;
$iTextSize = 20;
$sFont = Phpfox::getParam('core.dir_static') . 'image/font/' . Phpfox::getParam('captcha.captcha_font');
if (!file_exists($sFont))
{
return $this->_writeFromString($sText);
}
$this->_imageCreate($iWidth, $iHeight);
$nBgColor = imageColorAllocate($this->_hImg, 255, 255, 255);
$nTxtColor = imageColorAllocate($this->_hImg, 0, 0, 0);
if (!($aBox = #imagettfbbox($iTextSize, 0, $sFont, $sText)))
{
return $this->_writeFromString($sText);
}
//Find out the width and height of the text box
$iTextW = $aBox[2] - $aBox[0];
$iTextH = $aBox[5] - $aBox[3];
if (function_exists('imagefilledellipse'))
{
$nNoiseColor = imagecolorallocate($this->_hImg, 207, 181, 181);
for ($i = 0; $i < ($iWidth*$iHeight) / 3; $i++)
{
imagefilledellipse($this->_hImg, mt_rand(0, $iWidth), mt_rand(0, $iHeight), 1, 1, $nNoiseColor);
}
}
$iImageLineColor = imagecolorallocate($this->_hImg, 207, 181, 181);
for ($i = 0; $i < ($iWidth*$iHeight) / 150; $i++)
{
imageline($this->_hImg, mt_rand(0, $iWidth), mt_rand(0, $iHeight), mt_rand(0, $iWidth), mt_rand(0, $iHeight), $iImageLineColor);
}
// Calculate the positions
$positionLeft = (($iWidth - $iTextW) / 2) - (20 + $iString);
$positionTop = (($iHeight - $iTextH) / 2);
for ($i = 0; $i < $iString; $i++)
{
if (!#imagettftext($this->_hImg, $iTextSize, 0, $positionLeft, 30, $nTxtColor, $sFont, $sText[$i]))
{
return $this->_writeFromString($sText);
}
$positionLeft += 20;
}
}
private function _writeFromString($sText)
{
$iString = strlen($sText);
$iWidth = (($iString + 5) * 6.4 * 2);
$iHeight = 40;
$this->_imageCreate($iWidth, $iHeight);
$nBgColor = imageColorAllocate($this->_hImg, 255, 255, 255);
$nTxtColor = imageColorAllocate($this->_hImg, 0, 0, 0);
$positionLeft = 20;
for ($i = 0; $i < $iString; $i++)
{
imagestring($this->_hImg, 5, $positionLeft, 12, $sText[$i], $nTxtColor);
$positionLeft += 15;
}
}
private function _imageCreate($iWidth, $iHeight)
{
$this->_hImg = imageCreate($iWidth, $iHeight);
}
}
?>
You may run into a problem or it could be your solution. Remember, the collation on your database also needs to be taken in consideration. If you are using utf8_general_ci then the ci means that it is case insensitive so no matter what you do on the code side, the database does not care if its upper or lower case. Test that on your search bar, look for some string, lets say a user, John Smith, and then search for the same string as john smith... If the search produces the same result, then your database doesn't care about case sensitive search. I don´t know where your captcha saves its answers, but if it does save them on the database, and its matching your questions in it, then it may not care if it is upper or lower case.
Just a reminder. You need to test that in your own enviroment.
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);
}
}