prepared statements - creating a single method* - php

FYI. ended up going with PDO solution as this was simpler.
I'm trying to add a single method to handle all queries to the database. I want the queries to use parameter binding. How do I handle a variable amount of function parameters in mysqli_stmt_bind_param()?
This post here led me to understand the pros of parameter binding.
Here is my example code..where I am currently stuck at is marked.
INPUT PARAMETERS
$query = "INSERT INTO b0 VALUES (?, ?, ?)"
$par_arr = {'bookmark', 'http://www.bookmark.com', 'tag'}
PROTOTYPE CODE
protected static function query($query, $par_arr)
{
if($statement=mysqli_prepare(one::$db, $query)
{
mysqli_stmt_bind_param($statement, "s", ...variable amount of parameters...);<----how should this be handled?
...

Update 2: If you experience any further problems with this code, then you should probably follow this advice and use PDO instead.
This is how you should be using call_user_func_array [docs]:
protected static function query($query, $types, $values) {
if($statement = mysqli_prepare(one::$db, $query) {
$parameters = array_merge(array($statement, $types), $values);
call_user_func_array('mysqli_stmt_bind_param', $parameters);
// ...
}
}
where $types is a string indicating the type of each value, as described in the mysqli_stmt_bind_param documentation (call_user_func_array is even mentioned there).
Update: It seems it is not that easy after all, and you have to create references to the values first:
foreach($values as $k => $v) {
$values[$k] = &$v;
}
$parameters = array_merge(array($statement, $types), $values);
call_user_func_array('mysqli_stmt_bind_param', $parameters);
// ...
call_user_func_array is for user defined functions per php.net
No it's not. The first parameter is of type callback, and the documentation says (emphasis mine):
A PHP function is passed by its name as a string. Any built-in or user-defined function can be used, except language constructs such as: array(), echo(), empty(), eval(), exit(), isset(), list(), print() or unset().
Next remark:
is just used to simplify syntax for passing arrays to user defined functions
Have you had a look at the examples? Each element of the array you pass to call_user_func_array will be passed as argument to the function you specify. Arrays are the only way to have a collection of values of variable size.

Because i find prepared statements boring, I am processing placeholders manually, and experience not a single problem of yours
private function prepareQuery($args)
{
$raw = $query = array_shift($args);
preg_match_all('~(\?[a-z?])~',$query,$m,PREG_OFFSET_CAPTURE);
$pholders = $m[1];
$count = 0;
foreach ($pholders as $i => $p)
{
if ($p[0] != '??')
{
$count++;
}
}
if ( $count != count($args) )
{
throw new E_DB_MySQL_parser("Number of args (".count($args).") doesn't match number of placeholders ($count) in [$raw]");
}
$shift = 0;
$qmarks = 0;
foreach ($pholders as $i => $p)
{
$pholder = $p[0];
$offset = $p[1] + $shift;
if ($pholder != '??')
{
$value = $args[$i-$qmarks];
}
switch ($pholder)
{
case '?n':
$value = $this->escapeIdent($value);
break;
case '?s':
$value = $this->escapeString($value);
break;
case '?i':
$value = $this->escapeInt($value);
break;
case '?a':
$value = $this->createIN($value);
break;
case '?u':
$value = $this->createSET($value);
break;
case '??':
$value = '?';
$qmarks++;
break;
default:
throw new E_DB_MySQL_parser("Unknown placeholder type ($pholder) in [$raw]");
}
$query = substr_replace($query,$value,$offset,2);
$shift+= strlen($value) - strlen($pholder);
}
$this->lastquery = $query;
return $query;
}
and thus an insert query can be called as simple as
$db->run("INSERT INTO table SET ?u",$data);

I have added the complete code to create a single method for select prepared statement and insert prepared statement, Please follow the instruction and read all the comments.
create database with the name 'test' and add the following query to create "users" table in the
CREATE TABLE IF NOT EXISTS `users` (
`users_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`first_name` varchar(100) NOT NULL,
`last_name` varchar(100) NOT NULL,
PRIMARY KEY (`users_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=10 ;
INSERT INTO `users` (`users_id`, `first_name`, `last_name`) VALUES
(1, 'daniel', 'martin'),
(2, 'daniel', 'martin');
<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
session_start();
class mysqli_access extends mysqli{
private $ip1;
private $dbconn;
private $hostname = HST; // hostname
private $username = USR; // username
private $password = PWD; // password
private $dbname = DBN; // datbase name
function mysqli_access()
{
$ip= $_SERVER['REMOTE_ADDR'];
$ip1="ip_".str_replace('.', "", $ip);
if(!is_resource($_SESSION[$ip1]))
{
$this->dbconn = new mysqli($this->hostname,$this->username,$this->password,$this->dbname);
$_SESSION[$ip1] = $this->dbconn;
$dbconn = $this->dbconn;
if( $this->connect_error ) {
$this->Display_error('', $this->connect_errno, $this->connect_error, __FUNCTION__);
}
}
else {
$this->dbconn = $_SESSION[$ip1]; // success
}
return $this->dbconn;
}
function SelectPrepared($sql,$types,$params,$rows = '')
{
$results = array();
if ($stmt = $this->dbconn->prepare($sql)) {
if($types&&$params)
{
$bind_names[] = $types;
for ($i=0; $i<count($params);$i++)
{
$bind_name = 'bind' . $i;
$$bind_name = $params[$i];
$bind_names[] = &$$bind_name;
}
$return = call_user_func_array(array($stmt,'bind_param'),$bind_names);
}
$stmt->execute(); /* execute query */
$meta = $stmt->result_metadata();
while ($field = $meta->fetch_field()) {
$var = $field->name;
$$var = null;
$fields_arr[$var] = &$$var;
}
call_user_func_array(array($stmt,'bind_result'),$fields_arr);
if($rows == 1){
while ($stmt->fetch()) {
$results = array();
foreach($fields_arr as $k => $v)
$results[$k] = $v;
}
}else{
$i = 0;
while ($stmt->fetch()) {
$results[$i] = array();
foreach($fields_arr as $k => $v)
$results[$i][$k] = $v;
$i++;
}
}
return $results;
}
}
public function InsertPrepared($tblName,$arrFieldNameValue,$replace_flag=0){
$TableName = $tblName;
if($replace_flag==0)
{
$sqlFirst ="INSERT INTO " . $TableName . "(";
}
if($replace_flag==1)
{
$sqlFirst ="INSERT IGNORE INTO " . $TableName . "(";
}
if($replace_flag==2)
{
$sqlFirst ="REPLACE INTO " . $TableName . "(";
}
$sqlSecond =" values(";
$params = array();
$types = '';
while(list($key,$value) = each($arrFieldNameValue))
{
$sqlFirst = $sqlFirst . $key . ",";
$sqlSecond = $sqlSecond . '?' . ",";
$params[] = $value;
$types = $types . $this->GetValType($value);
}
$sqlFirst = substr($sqlFirst,0,strlen($sqlFirst)-1) . ") ";
$sqlSecond = substr($sqlSecond,0,strlen($sqlSecond)-1) .")";
$sql = $sqlFirst . $sqlSecond;
if ($stmt = $this->dbconn->prepare($sql)) {
if($types&&$params)
{
$bind_names[] = $types;
for ($i=0; $i<count($params);$i++)
{
$bind_name = 'bind' . $i;
$$bind_name = $params[$i];
$bind_names[] = &$$bind_name;
}
$return = call_user_func_array(array($stmt,'bind_param'),$bind_names);
}
$stmt->execute(); /* execute query */
}
return mysqli_insert_id($this->dbconn);
}
private function GetValType($Item)
{
switch (gettype($Item)) {
case 'NULL':
case 'string':
return 's';
break;
case 'integer':
return 'i';
break;
case 'blob':
return 'b';
break;
case 'double':
return 'd';
break;
}
return 's';
}
}
class Model_NAME extends mysqli_access
{
function Model_NAME() {
$this->tablename = TABLENAME;
$this->mysqli_access();
}
##---------------------------- Custom function start from here -----------------#
## fetch settings values
function getUserRow($id,$key) {
$sql ="SELECT first_name,last_name FROM ".$this->tablename." WHERE first_name=? and users_id = ?";
$param = "si";
$array_of_params[] = addslashes($key);
$array_of_params[] = addslashes($id);
$result= $this->SelectPrepared($sql,$param,$array_of_params,1);
//last parameter 1 use if want fetch single row , other wise function will return multi dimensional array
return $result;
}
## fetch settings values
function getUserRows($last_name) {
$sql ="SELECT first_name,last_name FROM ".$this->tablename." WHERE last_name= ?";
$param = "s";
$array_of_params[] = addslashes($last_name);
$result= $this->SelectPrepared($sql,$param,$array_of_params);
//last parameter 1 use if want fetch single row , other wise function will return multi dimensional array
return $result;
}
function addValue($Array) {
return $this->InsertPrepared( $this->tablename , $Array);
}
}
// configuration
define('HST','localhost');
define('USR','root');
define('PWD','techmodi');
define('DBN','test');
define('TABLENAME','users');
$obj = new Model_NAME();
$arr = array();
$arr['first_name'] = addslashes("daniel");
$arr['last_name'] = addslashes("martin");
$obj->addValue($arr); // for insert records
// after inserting get the records
$singleRow = $obj->getUserRow(1,'daniel'); // for select single records
$multiRow =$obj->getUserRows('martin'); // for select records
echo '<pre>';
echo '<br/>-------- Single Records -----------------<br/>';
print_r($singleRow);
echo '<br/>-------- Multiple Records-----------------<br/>';
print_r($multiRow);
?>

Related

Prepared Statements not working in mySQL / PHP [duplicate]

This question already has answers here:
mysqli_stmt::bind_result(): Number of bind variables doesn't match number of fields in prepared statement
(2 answers)
Closed 1 year ago.
For some reason I keep getting this error when attempting to run prepared query with mysqli
mysqli_stmt::bind_result(): Number of bind variables doesn't match
number of fields in prepared statement
This db class works fine until I try to use a query with LEFT OUTER JOIN
I'm wondering if anyone knows why? I'll post the query, schema, etc.. below.
NOTE: I saw one question on here that suggested I specifically spell out all the field names I want to select, rather than use '*'(star). There are A LOT of fields involved and I spent almost an hour typing them all out. When I tested, it didn't change anything. I have omitted that and returned to using star just in case anyone was going to suggest I type them all out. Already tried. Doesn't help.
ALSO: This query works fine if I put it straight into phpMyAdmin, so it's a working query. Just throwing an error when trying to bind the result for some reason. Even if I remove the multiple joins and just have one left join it still throws the error about not having the correct parameter count. I don't get it.
Query Output by PHP
SELECT * FROM `SlipMaster`
left outer join `SlipMain`
on `SlipMaster`.`slipCode` = `SlipMain`.`slipCode`
left outer join `ContractMain`
on `SlipMain`.`slipContractId` = `ContractMain`.`id`
left outer join `ClientMain`
on `SlipMain`.`slipClientId` = `ClientMain`.`id`
left outer join `PaymentMain`
on `ContractMain`.`contractPaymentId` = `PaymentMain`.`id`
left outer join `VesselMain`
on `SlipMain`.`slipVesselId` = `VesselMain`.`id`
WHERE 1 = ?
PHP CODE USING MYSQLI DB CLASS
$from = '
`SlipMaster`
left outer join `SlipMain`
on `SlipMaster`.`slipCode` = `SlipMain`.`slipCode`
left outer join `ContractMain`
on `SlipMain`.`slipContractId` = `ContractMain`.`id`
left outer join `ClientMain`
on `SlipMain`.`slipClientId` = `ClientMain`.`id`
left outer join `PaymentMain`
on `ContractMain`.`contractPaymentId` = `PaymentMain`.`id`
left outer join `VesselMain`
on `SlipMain`.`slipVesselId` = `VesselMain`.`id`';
$dbi->new_query();
$dbi->add_param('i', '1');
$dbi->select($from, '*', '1=?');
PHP MYSQLI DB CLASS
<?php
class mysqliObject {
public $user = "";
public $pass = "";
public $name = "";
public $host = "";
public $_db;
public $_config;
public $MYSQLI_LINK = FALSE;
public $rows = FALSE;
public $last_error = FALSE;
public $last_query = FALSE;
public $result = FALSE;
public $last_id = FALSE;
public $paramTypeArray = [];
public $paramBindArray = [];
public function __construct() {
}
public function __destruct() {
$this->close();
}
public function connect() {
$this->host = $this->_config->get('DBHOST');
$this->name = $this->_config->get('DBNAME');
$this->user = $this->_config->get('DBUSER');
$this->pass = $this->_config->get('DBPASS');
$this->MYSQLI_LINK = new mysqli($this->host, $this->user, $this->pass, $this->name);
}
public function setDatabase($databaseConnection) {
$this->_db = $databaseConnection;
}
public function setConfig($config) {
$this->_config = $config;
}
public function close() {
#mysqli_close($this->MYSQLI_LINK);
}
public function get_hash($p) {
return password_hash($p, PASSWORD_BCRYPT, array("cost" => 10));
}
public function check_password($p, $h) {
return (password_verify($p, $h)) ? true : false;
}
public function get_rndkey($length=32) {
$random_string="";
while(strlen($random_string)<$length && $length > 0) {
$randnum = mt_rand(0,61);
$random_string .= ($randnum < 10) ?
chr($randnum+48) : ($randnum < 36 ?
chr($randnum+55) : $randnum+61);
}
return $random_string;
}
public function escape($value) {
return mysqli_real_escape_string($this->MYSQLI_LINK, $value);
}
public function get_lastid() {
return $this->MYSQLI_LINK->insert_id;
}
public function new_query() {
$this->paramTypeArray = Array();
$this->paramBindArray = Array();
}
public function add_param($t, $d) {
$this->paramTypeArray[] = $t;
$this->paramBindArray[] = $d;
}
// Shortcut for Select Method
public function s($t,$x, $d, $w) {
$this->new_query();
foreach($d as $v) {
$this->add_param($v['t'], $v['v']);
}
return $this->select($t, $x, $w) ? $this->result : false;
}
public function select($t, $d, $c) {
/* Types: s = string, i = integer, d = double, b = blob */
$a_params = array();
$param_type = '';
$n = count($this->paramTypeArray);
for($i = 0; $i < $n; $i++) {
$param_type .= $this->paramTypeArray[$i];
}
$a_params[] = & $param_type;
for($i = 0; $i < $n; $i++) {
$a_bind_params[] = $this->paramBindArray[$i];
}
for($i = 0; $i < $n; $i++) {
$a_params[] = & $a_bind_params[$i];
}
$q = 'SELECT '.$d.' FROM '.$t.' WHERE '.$c;
$s = $this->MYSQLI_LINK->prepare($q);
if($s === false) {
trigger_error('Wrong SQL: ' . $q . ' Error: ' . $this->MYSQLI_LINK->errno . ' ' . $this->MYSQLI_LINK->error, E_USER_ERROR);
}
call_user_func_array(array($s, 'bind_param'), $a_params);
$s->execute();
$meta = $s->result_metadata();
while ($field = $meta->fetch_field()) {
$var = $field->name;
$$var = null;
$fields[$var] = &$$var;
}
call_user_func_array(array($s,'bind_result'),$fields);
$i = 0;
while ($s->fetch()) {
$results[$i] = [];
foreach($fields as $k => $v) {
$results[$i][$k] = $v;
}
$i++;
}
$s->close();
$this->last_query = $q;
if (count($results) > 0) {
$this->result = $results;
return TRUE;
} else {
$this->last_error = mysqli_error($this->MYSQLI_LINK);
return FALSE;
}
return FALSE;
}
public function delete($t, $c) {
$a_params = array();
$param_type = '';
$n = count($this->paramTypeArray);
for($i = 0; $i < $n; $i++) {
$param_type .= $this->paramTypeArray[$i];
}
$a_params[] = & $param_type;
for($i = 0; $i < $n; $i++) {
$a_bind_params[] = $this->paramBindArray[$i];
}
for($i = 0; $i < $n; $i++) {
$a_params[] = & $a_bind_params[$i];
}
$q = "delete from ".$t." where ".$c;
$s = $this->MYSQLI_LINK->prepare($q);
$this->last_query = $q;
if($s === false) {
trigger_error('Wrong SQL: ' . $q . ' Error: ' . $this->MYSQLI_LINK->errno . ' ' . $this->MYSQLI_LINK->error, E_USER_ERROR);
}
call_user_func_array(array($s, 'bind_param'), $a_params);
$s->execute();
$count = $s->affected_rows;
$s->close();
if ($count > 0) {
$this->rows = $count;
return TRUE;
} else {
$this->last_error = mysqli_error($this->MYSQLI_LINK);
return FALSE;
}
}
public function insert($t, $d) {
$a_params = array();
$param_type = '';
$n = count($this->paramTypeArray);
for($i = 0; $i < $n; $i++) {
$param_type .= $this->paramTypeArray[$i];
}
$a_params[] = & $param_type;
for($i = 0; $i < $n; $i++) {
$a_bind_params[] = $this->paramBindArray[$i];
}
for($i = 0; $i < $n; $i++) {
$a_params[] = & $a_bind_params[$i];
}
$query_cols = 'insert into '.$t.' (';
$query_vals = 'values (';
while (list($key, $value) = each($d)) {
$query_cols .= $value . ', ';
$query_vals .= '?, ';
}
$query_cols = substr($query_cols, 0, strlen($query_cols) - 2);
$query_vals = substr($query_vals, 0, strlen($query_vals) - 2);
$q = $query_cols . ') ' . $query_vals . ')';
$this->last_query = $q;
$s = $this->MYSQLI_LINK->prepare($q);
if($s === false) {
trigger_error('Wrong SQL: ' . $q . ' Error: ' . $this->MYSQLI_LINK->errno . ' ' . $this->MYSQLI_LINK->error, E_USER_ERROR);
}
call_user_func_array(array($s, 'bind_param'), $a_params);
$s->execute();
$count = $s->affected_rows;
$this->last_id = $s->insert_id;
$s->close();
if ($count > 0) {
$this->rows = $count;
return TRUE;
} else {
$this->last_error = mysqli_error($this->MYSQLI_LINK);
return FALSE;
}
}
public function update($t, $d, $c) {
$a_params = array();
$param_type = '';
$n = count($this->paramTypeArray);
for($i = 0; $i < $n; $i++) {
$param_type .= $this->paramTypeArray[$i];
}
$a_params[] = & $param_type;
for($i = 0; $i < $n; $i++) {
$a_bind_params[] = $this->paramBindArray[$i];
}
for($i = 0; $i < $n; $i++) {
$a_params[] = & $a_bind_params[$i];
}
$q = 'update ' . $t . ' set ';
while (list($key, $value) = each($d)) {
$q .= $value . ' = ?, ';
}
//strip comma off end of variable
$q = substr($q, 0, strlen($q) - 2);
$q .= ' where ' . $c;
$this->last_query = $q;
$s = $this->MYSQLI_LINK->prepare($q);
if($s === false) {
trigger_error('Wrong SQL: ' . $q . ' Error: ' . $this->MYSQLI_LINK->errno . ' ' . $this->MYSQLI_LINK->error, E_USER_ERROR);
}
call_user_func_array(array($s, 'bind_param'), $a_params);
$s->execute();
$count = $s->affected_rows;
$s->close();
if ($count > 0) {
$this->rows = $count;
return TRUE;
} else {
$this->last_error = mysqli_error($this->MYSQLI_LINK);
return FALSE;
}
}
} // End Class
Simplified Schema
NOTE: Let me know if you need me to post a more complete schema. This just shows the fields that are linking the joins. All fields are INT(255) unique, id fields are INT(255) AI PRIMARY
SlipMaster links to SlipMain via slipCode, all others link foreign key
to Primary id
SlipMaster (id, slipCode)
SlipMain (id, slipCode, slipContractId, slipClientId, slipVesselId)
ContractMain (id, contractPaymentId)
ClientMain (id)
PaymentMain (id)
VesselMain (id)
* is all the fields in all the tables you are JOINing together. This includes duplicates, such as slipCode, which exists at least twice.
Plan A: Spell out the fields that you really want. This will make it easier to count them and know how many to "bind". And it will make it clear what order to bind them in.
Plan B: Don't use bind_result; simply fetch the result into an array or hash.
Plan C: Do both. (I prefer this.)
#Notorious, I think the answer to your problem is not the sql but to the bind_result() function that you are using.
Explaining furthur, the bind_result() function is used to assign retrieved data from the database to variables. So the number of fields selected (returned from the database) must be equal to the number of binded results.
For instance,
If I selected the firstname and the lastname fields from the database I must use
bind_result($firstname, $lastname);
So as you can see the number of variables in the bind_result() is equal to the number of fields selected.
For your case you are selecting everything from the first db to second to third ..blablabla till the last db. So make sure the number of fields assigned to the the bind_result() function is equal to the number of all the fields returned. That is the sum of the total number of columns in all the databases.
So you got a lot of typing to do but at least its for the best.
Good luck and I hope it helped.

dynamic prepared insert statement

Let me preface that I just started learning prepared statements so much of this might just be to much to grasp, but I want to try.
I am trying to make a dynamic create function within my DatabaseObject class. The function would take any number of values of potentially any number of the different allowed data types. Unfortunately nothing I have tried has worked. Here is the code.
public function create() {
$db = Database::getInstance();
$mysqli = $db->getConnection();
//array of escaped values of all types in the object
$attributes = $this->sanitized_attributes();
$check = $mysqli->stmt_init();
$paramType = array();
$types = ''; $bindParam = array(); $where = ''; $count = 0;
foreach($attributes as $key=>$val)
{
$types .= 'i';
$bindParam[] = '$p'.$count.'=$param["'.$key.'"]';
$where .= "$key = ? AND ";
$count++;
}
$sql_query = "INSERT INTO `".static::$table_name."` ";
$sql_query .= "VALUES (";
foreach ($attributes as $key => $value) {
$valueType = gettype($value);
if ($valueType == 'string') {
$sql_query .= "?,";
array_push($paramType, "s");
} else if ($valueType == 'integer') {
$sql_query .= "?,";
array_push($paramType, "i");
} else if ($valueType == 'double') {
$sql_query .= "?,";
array_push($paramType, "d");
} else {
$sql_query .= "?,";
array_push($paramType, "b");
}
}
$sql_query .= ")";
}
At this point I am completely lost as to what I am suppose to do.
I have gotten simple prepared statements to work, but this one is much more complicated and dynamic and I don't know if I handled the process up to this point correctly and what to do following the sql_query in order to get this to work. All the questions here have left me confused so maybe if I got guidance with my current code to see where i went wrong it will assist.
I appreciate your time.
public function create() {
$db = Database::getInstance();
$mysqli = $db->getConnection();
$attributes = $this->sanitized_attributes();
$tableName = static::$table_name;
$columnNames = array();
$placeHolders = array();
$values = array();
foreach($attributes as $key=>$val)
{
// skip identity field
if ($key == static::$identity)
continue;
$columnNames[] = '`' . $key. '`';
$placeHolders[] = '?';
$values[] = $val;
}
$sql = "Insert into `{$tableName}` (" . join(',', $columnNames) . ") VALUES (" . join(',', $placeHolders) . ")";
$statement = $mysqli->stmt_init();
if (!$statement->prepare($sql)) {
die("Error message: " . $mysqli->error);
return;
}
$bindString = array();
$bindValues = array();
// build bind mapping (ssdib) as an array
foreach($values as $value) {
$valueType = gettype($value);
if ($valueType == 'string') {
$bindString[] = 's';
} else if ($valueType == 'integer') {
$bindString[] = 'i';
} else if ($valueType == 'double') {
$bindString[] = 'd';
} else {
$bindString[] = 'b';
}
$bindValues[] = $value;
}
// prepend the bind mapping (ssdib) to the beginning of the array
array_unshift($bindValues, join('', $bindString));
// convert the array to an array of references
$bindReferences = array();
foreach($bindValues as $k => $v) {
$bindReferences[$k] = &$bindValues[$k];
}
// call the bind_param function passing the array of referenced values
call_user_func_array(array($statement, "bind_param"), $bindReferences);
$statement->execute();
$statement->close();
return true;
}
I want to make special note that I did not find the solution myself. I had a long time developer find this solution and wanted to post it for those that might want to know.
I accidently found your old post as I was trying myself to find a solution to the exact same problem. My code seems a bit more advantagous as there is only one loop included. Therefore I will add it as a possible improvement to this post:
$sqlquery = $this->MySQLiObj->prepare($dummy);
$paramQuery = array();
$paramQuery[0] = '';
$n = count($valueArray);
for($i = 0; $i < $n; $i++) {
$checkedDataType = $this->returnDataType($valueArray[$i]);
if($checkedkDataType==false) {
return false;
}
$paramQuery[0] .= $checkedDataType;
/* with call_user_func_array, array params must be passed by reference -> & */
$paramQuery[] = &$valueArray[$i];
}
/*In array(): sqlquery(object)->bind_param(method)*/
call_user_func_array(array($sqlquery, 'bind_param'), $paramQuery);
$sqlquery->execute();
/*Can be used identical to $result = $mysqli->query()*/
$result = $this->MySQLiObj->get_result();
$sqlquery->close();
Utilizing the function returnDataType() with a switch statement, which might be faster if there is a preference for a certain data type.
private function returnDataType($input) {
switch(gettype($input)) {
case string: return 's';
case double: return 'd';
case integer: return 'i';
default: $this->LOG->doLog("Unknown datatype during database access."); return 's';
}
}

using prepared statements and dynamic param in mysqli

I'm using a prepared statement and these functions are part of a mysqli class .They work well for singl condition But do not right answer for multiple condition like this:
SelectByOrderCondi('user','username=? AND name=? AND email=? ' , $Array )
Here's my functions :
public function SelectByOrderCondi($Table_Name, $Conditions='' ,$Array_Conditions_Limit=null, $OrderBy='', $Limit='', $Selected_Fields='*')
{
$Query = "SELECT ".$Selected_Fields." FROM ".$Table_Name;
if(!empty($Conditions))
$Query .= " WHERE ".$Conditions;
if(!empty($OrderBy))
$Query .= " ORDER BY ".$OrderBy;
if(!empty($Limit))
$Query .= " LIMIT ".$Limit;
$Statment = $this->ConnectionResult->prepare($Query);
if(isset($Array_Conditions_Limit) )
{
$Statment = $this->DynamicBindVariables($Statment, $Array_Conditions_Limit);
$Statment->execute();
return $Statment->get_result();
}
else
return false ;
}
Add my class this function:
Private function GetType($Item)
{
switch (gettype($Item)) {
case 'NULL':
case 'string':
return 's';
break;
case 'integer':
return 'i';
break;
case 'blob':
return 'b';
break;
case 'double':
return 'd';
break;
}
return '';
}
and change DynamicBindVariables functions as follows:
public function DynamicBindVariables($Statment, $Params)
{
if (is_array($Params) && $Params != null)
{
// Generate the Type String (eg: 'issisd')
$Types = '';
foreach($Params as $Param)
{
$Types .= $this->GetType($Param);
}
// Add the Type String as the first Parameter
$Bind_names[] = $Types;
// Loop thru the given Parameters
for ($i=0; $i<count($Params);$i++)
{
$Bind_name = 'bind' . $i;
// Add the Parameter to the variable
$$Bind_name = $Params[$i];
// Associate the Variable as an Element in the Array
$Bind_names[] = &$$Bind_name;
}
// Call the Function bind_param with dynamic Parameters
call_user_func_array(array($Statment,'bind_param'), $Bind_names);
}
else
{
$Types .= $this->GetType($Param);
$Statment->bind_param($Types ,$Params);
}
return $Statment;
}
Now it works properly
Just side note, your code might be incorrect for determining types, see this test:
var_dump(is_int("1")); //bool(false)
var_dump(is_float("1.1")); //bool(false)
var_dump(is_string("1.1")); //bool(true)
You can use:
ctype_digit() for integers or if((int) $Param == $Param)
is_numeric() for float or if((float)$Param == $Param)

Mysqli get_result alternative

I've just changed all my sql queries to prepared statements using mysqli. To speed this process up I created a function (called performQuery) which replaces mysql_query. It takes the query, the bindings (like "sdss") and the variables to pass in, this then does all the perpared statement stuff. This meant changing all my old code was easy. My function returns a mysqli_result object using mysqli get_result().
This meant I could change my old code from:
$query = "SELECT x FROM y WHERE z = $var";
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)){
echo $row['x'];
}
to
$query = "SELECT x FROM y WHERE z = ?";
$result = performQuery($query,"s",$var);
while ($row = mysql_fetch_assoc($result)){
echo $row['x'];
}
This works fine on localhost, but my web hosting server does not have mysqlnd available, therefore get_result() does not work. Installing mysqlnd is not an option.
What is the best way to go from here? Can I create a function which replaces get_result(), and how?
Here is a neater solution based on the same principle as lx answer:
function get_result( $Statement ) {
$RESULT = array();
$Statement->store_result();
for ( $i = 0; $i < $Statement->num_rows; $i++ ) {
$Metadata = $Statement->result_metadata();
$PARAMS = array();
while ( $Field = $Metadata->fetch_field() ) {
$PARAMS[] = &$RESULT[ $i ][ $Field->name ];
}
call_user_func_array( array( $Statement, 'bind_result' ), $PARAMS );
$Statement->fetch();
}
return $RESULT;
}
With mysqlnd you would normally do:
$Statement = $Database->prepare( 'SELECT x FROM y WHERE z = ?' );
$Statement->bind_param( 's', $z );
$Statement->execute();
$Result = $Statement->get_result();
while ( $DATA = $Result->fetch_array() ) {
// Do stuff with the data
}
And without mysqlnd:
$Statement = $Database->prepare( 'SELECT x FROM y WHERE z = ?' );
$Statement->bind_param( 's', $z );
$Statement->execute();
$RESULT = get_result( $Statement );
while ( $DATA = array_shift( $RESULT ) ) {
// Do stuff with the data
}
So the usage and syntax are almost identical. The main difference is that the replacement function returns a result array, rather than a result object.
I encountered the same problem and solved it using the code provided in the answer of
What's wrong with mysqli::get_result?
My function looks like this now (error handling stripped out for clarity):
function db_bind_array($stmt, &$row)
{
$md = $stmt->result_metadata();
$params = array();
while($field = $md->fetch_field()) {
$params[] = &$row[$field->name];
}
return call_user_func_array(array($stmt, 'bind_result'), $params);
}
function db_query($db, $query, $types, $params)
{
$ret = FALSE;
$stmt = $db->prepare($query);
call_user_func_array(array($stmt,'bind_param'),
array_merge(array($types), $params));
$stmt->execute();
$result = array();
if (db_bind_array($stmt, $result) !== FALSE) {
$ret = array($stmt, $result);
}
$stmt->close();
return $ret;
}
Usage like this:
$userId = $_GET['uid'];
$sql = 'SELECT name, mail FROM users WHERE user_id = ?';
if (($qryRes = db_query($db, $sql, 'd', array(&$userId))) !== FALSE) {
$stmt = $qryRes[0];
$row = $qryRes[1];
while ($stmt->fetch()) {
echo '<p>Name: '.$row['name'].'<br>'
.'Mail: '.$row['mail'].'</p>';
}
$stmt->close();
}
I found the anonymous advice posted as a note at the API documentation page for mysqli_stmt::get_result very useful (I couldn't think of a better way than the eval trick), as we very often want to fetch_array() on our result. However, because I wanted to cater for a generic database object, I found it a problem that the code assumed numeric array was fine for all callsites, and I needed to cater for all callers using assoc arrays exclusively. I came up with this:
class IImysqli_result {
public $stmt, $ncols;
}
class DBObject {
function iimysqli_get_result($stmt) {
$metadata = $stmt->result_metadata();
$ret = new IImysqli_result;
if (!$ret || !$metadata) return NULL; //the latter because this gets called whether we are adding/updating as well as returning
$ret->ncols = $metadata->field_count;
$ret->stmt = $stmt;
$metadata->free_result();
return $ret;
}
//this mimics mysqli_fetch_array by returning a new row each time until exhausted
function iimysqli_result_fetch_array(&$result) {
$stmt = $result->stmt;
$stmt->store_result();
$resultkeys = array();
$thisName = "";
for ( $i = 0; $i < $stmt->num_rows; $i++ ) {
$metadata = $stmt->result_metadata();
while ( $field = $metadata->fetch_field() ) {
$thisName = $field->name;
$resultkeys[] = $thisName;
}
}
$ret = array();
$code = "return mysqli_stmt_bind_result(\$result->stmt ";
for ($i=0; $i<$result->ncols; $i++) {
$ret[$i] = NULL;
$theValue = $resultkeys[$i];
$code .= ", \$ret['$theValue']";
}
$code .= ");";
if (!eval($code)) {
return NULL;
}
// This should advance the "$stmt" cursor.
if (!mysqli_stmt_fetch($result->stmt)) {
return NULL;
}
// Return the array we built.
return $ret;
}
}

How should one signify to a caller in PHP that a function accepts a variable number of arguments?

It has come down from high places that a webapp I've been working on needs to move to stored procedures for everything it does in the database. To that end, I have taken to enforcing that constraint by writing a new database layer on top of mysqli which exposes only the "allowed" behavior. Consider what I have so far:
class Cas_Database
{
private $mysqli;
private $mode;
public function __construct(...)
{
... //Ommitted
}
public function Transaction(/* callable */ $func)
{
$mysqli->autocommit(false);
try
{
$func($this);
$mysqli->commit();
$mysqli->autocommit(true);
}
catch (Exception $ex)
{
$mysqli->rollback();
$mysqli->autocommit(true);
throw $ex;
}
}
public function MultiProcedure($schema, $func)
{
$args = func_num_args() - 2;
$sql = "CALL `{$this->mode}_{$schema}`.`{$func}` (";
if ($args >= 1)
{
$sql .= '? ';
for ($idx = 1; $idx < $args; ++$idx)
{
$sql .= ', ?';
}
}
$sql .= ')';
$stmt = $mysqli->prepare($sql);
$typeStr = '';
$refArgs = array(null);
for ($idx = 0; $idx < $args; ++$idx)
{
$argIndex = $idx + 2;
$arg = func_get_arg($argIndex);
$refArgs[] = &$arg;
if (is_int($arg))
{
$typeStr .= 'i';
}
else if (is_float($arg))
{
$typeStr .= 'f';
}
else
{
$typeStr .= 's';
}
}
$refArgs[0] = $typeStr;
call_user_func_array(array($stmt, 'bind_param'), $refArgs);
if ($stmt->execute() !== true)
{
$error = $stmt->error;
$stmt->close();
throw new Exception($error);
}
$mysqlAnswer = $stmt->get_result();
$results = array();
while (($answerRow = $mysqlAnswer->fetch_assoc()) !== null)
{
$results[] = $answerRow;
}
$stmt->close();
return $results;
}
}
Note how the MultiProcedure function expects multiple arguments from the user. Is there a way to specify that in the contract of the function so that users know what to look for, or are they forced to read the method to find out?
Use phpDocumentor's #param syntax to mention it in the documentation of the method. It will show up when you generate the docs, and in the developer's IDE at the time the method will be used.
Write the parameter name as $paramn,... and in the description write that there can be any number of arguments.

Categories