I am making a PDO update statement but it is entering 0's on empty values.
I want a empty value to enter null
I want a zero value to enter zero
Here is my code:
include 'dbconfig.php';
$id = $_POST['id'];
$data = $_POST['data'];
try {
$options = [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
\PDO::ATTR_EMULATE_PREPARES => false,
];
$pdo = new PDO("mysql:charset=utf8mb4;host=$servername;dbname=$dbname", $username, $password);
$setStr = "";
$values = array();
foreach($data as $field => $value) {
$setStr .= "$field=:$field,";
$values[$field] = $value;
}
$setStr = rtrim($setStr, ",");
$values['id'] = $id;
$stmt = $pdo->prepare("UPDATE products SET $setStr WHERE id = :id");
$stmt->execute($values);
$count = $stmt->rowCount();
if ($count > 0) {
echo json_encode(array('response'=>'success','message'=>'Product ID # '.$id." successfully updated."));
}else{
echo json_encode(array('response'=>'danger','message'=>'Product not successfully updated'));
}
}catch(PDOException $e){
echo json_encode(array('response'=>'danger','message'=>$e->getMessage()));
}
$conn = null;
What is the best way to do this? Thank you
Check for an empty string in your loop, and convert it to null.
foreach($data as $field => $value) {
$setStr .= "$field=:$field,";
$values[$field] = $value === "" ? null : $value;
}
PDOStatement::execute considers every parameter to be a string. In some databases the driver deals with this without issue, but if you want to specifically type values you need instead to use bindValue. With this typing, we can type null (or empty) values to the database-null type (instead of whatever the column default is) - see my bindEmptyAsNull function.
Also, since I'm using a trusted source for the column names, I can safely use your $setStr pattern for building the update params, but note you might not want to update a column that isn't included in the $dangerData associative array (as it is, if it isn't submitted, the column will be cleared).
<?php
//... your setup code, including $pdo
// List all the names of the columns in the products table here - you havent' provided enough info so I'm guessing
$keys=["name","cost","weight_grams"];
$dangerId = $_POST['id'];
$dangerData = $_POST['data'];
/**
* Convert null values into PARAM_NULL types, not
* #param $type Should be one of the [PDO::PARAM_*](https://www.php.net/manual/en/pdo.constants.php) constants
*/
function bindEmptyAsNull($stmt,$name,$value,$type=PDO::PARAM_STR) {
//If you want empty string to be considered null too:
//if ($value===null || $value==="") {
if ($value===null) {
//Note the column needs to support null types
$stmt->Value($name,null,PDO::PARAM_NULL);
} else {
$stmt->bindValue($name,$value,$type);
}
}
//Build the set string
$setStr='';
foreach($keys as $col) {
$setStr.=$col.'=:'.$col.',';
}
$setStr=substr($set,0,-1);//Remove the trailing comma
//Create the statement
$stmt=$pdo->prepare("UPDATE products SET $setStr WHERE id=:id");
//Bind the danger values
// NOTE: The only way you could automate this (re-read the keys array) is to also have an
// associative array of key:type mapping too
$stmt->bindValue(":id",$dangerId,PDO::PARAM_INT);
bindEmptyAsNull($stmt,":name",$dangerData["name"]);
bindEmptyAsNull($stmt,":cost",$dangerData["cost"]);
bindEmptyAsNull($stmt,":weight_grams",$dangerData["weight_grams"],PDO::PARAM_INT);
$stmt->execute();
// .. Further processing
Related
I'm getting null values after I run the DBEscape($data) function that is for SQL injection protection. Can someone help?
My inputs are all multiple arrays, ex: name="quote[][dt_flight]", name="quote[][acft]", etc.
Method is POST.
function DBEscape($data){
$link = DBConect();
if(!is_array($data)){
$data = mysqli_real_escape_string($link,$data);
}
else {
$arr = $data;
foreach ($arr as $key => $value){
$key = mysqli_real_escape_string($link, $key);
$value = mysqli_real_escape_string($link, $value);
$data[$key] = $value;
}
}
DBClose($link);
return $data;
}
function DBCreate($table, array $data, $insertId = false){
$table = DB_PREFIX.'_'.$table;
$data = DBEscape($data);
var_dump($data);
$fields = implode(", ", array_keys($data));
$values = "'".implode("', '", $data)."'";
$query = "INSERT INTO {$table} ({$fields}) VALUES ({$values});";
var_dump($query);
return DBExecute($query, $insertId);
}
if(isset($_POST["quote"]) && is_array($_POST["quote"])){
foreach($_POST["quote"]["dt_flight"] as $key => $text_field){
$last_id = DBCreate('quote',$_POST['quote'],true);
$i++;
}
}
The connection works since it is inserting the rows into the tables. I used vardump before and after the DBEscape to figure out that it is deleting the values, the keys are fine.
PS: The proposed answer is for a single variable not an array.
As you can see in your var_dump-result, the data you sent to DBCreate and thus to DBEscape looks like
array(
'dt_flight' => array(0 => '2018-06-13'),
'acft' => array(0 => 'VQ-BFD',
// and so on
)
Therfore the data you sent to
// $value = array(0 => '2018-06-13') here
$value = mysqli_real_escape_string($link, $value);
And well, mysqli_real_escape_string doesn't like arrays very much, thus will return NULL and thus inserting empty data in your table.
You most likely want to resolve this error within your foreach($_POST["quote"]["dt_flight"]) loop, since I suppose you sent multiple flight-data:
foreach($_POST["quote"]["dt_flight"] as $key => $text_field) {
// $key would be 0, for $_POST["quote"]["dt_flight"][0] = '2018-06-13'
$keyData = [];
foreach($_POST["quote"] as $field => $allFieldValues) {
// Walk over every field, and add the value for the same $key
if (is_array($data) && isset($allFieldValues[$key])) {
// Would add for example $keyData['acft'] = $_POST['quote']['acft'][0] = 'VQ-BFD';
$keyData[$field] = $allFieldValues[$key];
}
}
var_dump($keyData);
// Would look like array(
// 'dt-flight' => '2018-06-13',
// 'acft' => 'VQ-BFD',
// and so on
// )
$last_id = DBCreate('quote',$keyData,true);
$i++;
}
Although this is not part of your question, I really suggest you also take care of my comment on your question about mysqli_real_escape_string not being a safe way to escape column-names (or table-names and so on). For example with following solution:
function DBCreate($table, array $data, $insertId = false) {
// For each table the known columns
$columns = array( 'quote' => array('dt_flight', 'acft', '...') );
// Verify valid table given
if (!isset($columns[$table])) {
throw new InvalidArgumentException('No such table: ' . $table);
}
// Remove everything from data where the key is not in $columns[$table]
// = Remove everything where the column-name is non-existing or even an attempt to hack your system
$data = array_intersect_key($data, array_fill_keys($columns[$table], null));
if (!count($data)) {
throw new InvalidArgumentException('No (valid) data given at all');
}
// Next, continue with your implementation
}
I have a function that should be updating a row, no errors what so ever in the logs. From what I see it should be working. I took the function from a update user function and tried to mimic it for the new feature.
Here is the data array posting to it.
$data = array('id' => $vid, 'name' => $vname, 'logo' => $vlogo, 'info' => $vinfo, 'site' => $vsite, 'est' => $vest);
The post works, I am doing a dump on the updatecompany page. So they do get set. I think it may be with the function. Any insight would be wonderful!
public static function updateCompany($toUpdate = array(), $company = null){
self::construct();
if( is_array($toUpdate) && !isset($toUpdate['id']) ){
if($company == null){
echo "No company ID set!";
}
$columns = "";
foreach($toUpdate as $k => $v){
$columns .= "`$k` = :$k, ";
}
$sql = self::$dbh->prepare("UPDATE companys SET {$columns} WHERE `id` = :id");
$sql->bindValue(":id", $company);
foreach($toUpdate as $key => $value){
$value = htmlspecialchars($value);
$sql->bindValue(":$key", $value);
}
$sql->execute();
}else{
return false;
}
}
$vid = $_POST["idnum"];
$vname = $_POST["name"];
$vlogo = $_POST["logo"];
$vinfo = $_POST["info"];
$vsite = $_POST["site"];
$vest = $_POST["est"];
I would maybe try using the bind array into your execute() method since you are just binding the values (I assume this is PDO). Another feature is to use an array to assemble the column portions and implode at the time of use.
public static function updateCompany($toUpdate = array(), $company = null)
{
# Also this may supposed to be: self::__construct(); ?? Notice the "__" before "construct"
self::construct();
if(is_array($toUpdate) && !isset($toUpdate['id'])) {
if(empty($company)){
# Throw exception, catch it in a parent wrapper
throw new \Exception("No company ID set!");
# Stop, no sense in continuing if an important part is missing
return;
}
foreach($toUpdate as $k => $v){
$bKey = ":{$k}";
# I would create a bind array here
$bind[$bKey] = $value;
# I generally save to an array here to implode later
$columns[] = "`{$k}` = {$bKey}";
}
# Add the id here
$bind[":id"] = $company;
# I would use a try here for troubleshooting PDO errors
try {
# Create sql with imploded columns
$sql = self::$dbh->prepare("UPDATE companys SET ".implode(",",$columns)." WHERE `id` = :id");
# Throw the bind array into the execute here
$sql->execute($bind);
}
catch(\PDOException $e) {
# I would only die here to see if there are any errors for troubleshooting purposes
die($e->getMessage());
}
} else {
return false;
}
}
Your update SQL could not work because you have comma in update value set.
See, you attached comma without any consideration:
$columns = "";
foreach($toUpdate as $k => $v){
$columns .= "`$k` = :$k, ";
}
Then the final SQL will look something like this:
UPDATE companys SET `name`=:name, `logo`=:logo, WHERE `id`=:id
Do you notice the comma just before WHERE? it should not be there!
So you should update the code like following:
$columns = "";
foreach($toUpdate as $k => $v){
if ($columns != "") $columns .= ",";
$columns .= "`$k` = :$k ";
}
This should be working.
or to no need to be aware of last comma try this:
$columns = array();
foreach($toUpdate as $k => $v){
$columns[] = "`$k` = :$k";
}
$sql = self::$dbh->prepare("UPDATE `companys` SET ".implode(',', $columns)." WHERE `id` = :id");
I'm trying to dynamically bind mysql_stmt parameters and get the result in an associative array. I've found this post here on Stack Overflow where Amber posted an answer with the following code:
Original post:
How to make a proper mysqli extension class with prepared statements?
"Assuming you're actually wanting to write your own version (as opposed to utilizing one of the existing libraries other answers have suggested - and those are good options, too)...
Here are a couple of functions which you may find it useful to examine. The first allows you to bind the results of a query to an associative array, and the second allows you to pass in two arrays, one an ordered array of keys and the other an associative array of data for those keys and have that data bound into a prepared statement:"
function stmt_bind_assoc (&$stmt, &$out) {
$data = mysqli_stmt_result_metadata($stmt);
$fields = array();
$out = array();
$fields[0] = $stmt;
$count = 1;
while($field = mysqli_fetch_field($data)) {
$fields[$count] = &$out[$field->name];
$count++;
}
call_user_func_array(mysqli_stmt_bind_result, $fields);
}
function stmt_bind_params($stmt, $fields, $data) {
// Dynamically build up the arguments for bind_param
$paramstr = '';
$params = array();
foreach($fields as $key)
{
if(is_float($data[$key]))
$paramstr .= 'd';
elseif(is_int($data[$key]))
$paramstr .= 'i';
else
$paramstr .= 's';
$params[] = $data[$key];
}
array_unshift($params, $stmt, $paramstr);
// and then call bind_param with the proper arguments
call_user_func_array('mysqli_stmt_bind_param', $params);
}
I tried studying the code to understand what it does and I've made the second function work properly but I don't know what I should do to be able to utilize the first function. How do I use it to retrieve an array similar to mysqli_result:: fetch_assoc()?
I want to be able to utilize the result in such a way like you used to do with:
while ($row = mysql_fetch_array($result)){
echo $row['foo']." ".$row['bar'];
}
Okay, here is a way to do it:
Edited, to fix bug when fetching multiple rows
$sql = "SELECT `first_name`,`last_name` FROM `users` WHERE `country` =? AND `state`=?";
$params = array('Australia','Victoria');
/*
In my real app the below code is wrapped up in a class
But this is just for example's sake.
You could easily throw it in a function or class
*/
// This will loop through params, and generate types. e.g. 'ss'
$types = '';
foreach($params as $param) {
if(is_int($param)) {
$types .= 'i'; //integer
} elseif (is_float($param)) {
$types .= 'd'; //double
} elseif (is_string($param)) {
$types .= 's'; //string
} else {
$types .= 'b'; //blob and unknown
}
}
array_unshift($params, $types);
// Start stmt
$query = $this->connection->stmt_init(); // $this->connection is the mysqli connection instance
if($query->prepare($sql)) {
// Bind Params
call_user_func_array(array($query,'bind_param'),$params);
$query->execute();
// Get metadata for field names
$meta = $query->result_metadata();
// initialise some empty arrays
$fields = $results = array();
// This is the tricky bit dynamically creating an array of variables to use
// to bind the results
while ($field = $meta->fetch_field()) {
$var = $field->name;
$$var = null;
$fields[$var] = &$$var;
}
$fieldCount = count($fieldNames);
// Bind Results
call_user_func_array(array($query,'bind_result'),$fields);
$i=0;
while ($query->fetch()){
for($l=0;$l<$fieldCount;$l++) $results[$i][$fieldNames[$l]] = $fields[$fieldNames[$l]];
$i++;
}
$query->close();
// And now we have a beautiful
// array of results, just like
//fetch_assoc
echo "<pre>";
print_r($results);
echo "</pre>";
}
The Answer from Emmanuel works fine, if only one row is selected! If the query select multiple rows, the $results-Array holds for every row a result, but the result is always filled with the last entry. With a little change in the fetch()-while it work well.
$sqlStmt is an string, filled with the mysql-query
$params is an array, filled with the variables that should passed
$results is an empty array, that holds the result
if (!is_string($sqlStmt) || empty($sqlStmt)) {
return false;
}
// initialise some empty arrays
$fields = array();
$results = array();
if ($stmt = $this->prepare($sqlStmt)) {
// bind params if they are set
if (!empty($params)) {
$types = '';
foreach($params as $param) {
// set param type
if (is_string($param)) {
$types .= 's'; // strings
} else if (is_int($param)) {
$types .= 'i'; // integer
} else if (is_float($param)) {
$types .= 'd'; // double
} else {
$types .= 'b'; // default: blob and unknown types
}
}
$bind_names[] = $types;
for ($i=0; $i<count($params);$i++) {
$bind_name = 'bind' . $i;
$$bind_name = $params[$i];
$bind_names[] = &$$bind_name;
}
call_user_func_array(array($stmt,'bind_param'),$bind_names);
}
// execute query
$stmt->execute();
// Get metadata for field names
$meta = $stmt->result_metadata();
// This is the tricky bit dynamically creating an array of variables to use
// to bind the results
while ($field = $meta->fetch_field()) {
$var = $field->name;
$$var = null;
$fields[$var] = &$$var;
}
// Bind Results
call_user_func_array(array($stmt,'bind_result'),$fields);
// Fetch Results
$i = 0;
while ($stmt->fetch()) {
$results[$i] = array();
foreach($fields as $k => $v)
$results[$i][$k] = $v;
$i++;
}
// close statement
$stmt->close();
}
Just to compare excellent answers from #Emmanuel and #matzino with the code you can get if choose PDO over mysqli:
$sql = "SELECT `first_name`,`last_name` FROM `users` WHERE `country` =? AND `state`=?";
$params = array('Australia','Victoria');
$stm = $query->prepare($sql);
$stm->execute($params);
$results = $stm->fetchAll(); // or fetch() or fetchColumn() depends on expected type
whoops, that's all?
After using the answer above I have figured out that there was some cleanup needed for myself, particularly the 'fieldNames[]' portion. The code below is in procedural style. I hope it will come of use to someone.
I cut the code from a class I made that can dynamically query data. There are a few things I removed to make it easier to read. In the class I have I allow the user to define definitions tables and foreign keys so that data entry on the front-end is restricted as well as filter and sort options for said related data. These are all parameters I removed as well as the automated query builder.
$query = "SELECT `first_name`,`last_name` FROM `users` WHERE `country` =? AND `state`=?";
$params = array('Australia','Victoria');
////////////// GENERATE PARAMETER TYPES IF ANY //////////////
// This will loop through parameters, and generate types. ex: 'ss'
$types = '';
$params_size = sizeof($params);
if($params_size > 0)
{
foreach($params as $param)
{
if(is_int($param))
{
$types .= 'i'; //integer
}else if(is_float($param))
{
$types .= 'd'; //double
}else if(is_string($param))
{
$types .= 's'; //string
}else
{
$types .= 'b'; //blob and unknown
}
}
array_unshift($params, $types);
}
////////////////////////////////////////////////////////////
// This is the tricky part to dynamically create an array of
// variables to use to bind the results
//below from http://php.net/manual/en/mysqli-result.fetch-field.php
/*
name The name of the column
orgname Original column name if an alias was specified
table The name of the table this field belongs to (if not calculated)
orgtable Original table name if an alias was specified
def Reserved for default value, currently always ""
db Database (since PHP 5.3.6)
catalog The catalog name, always "def" (since PHP 5.3.6)
max_length The maximum width of the field for the result set.
length The width of the field, as specified in the table definition.
charsetnr The character set number for the field.
flags An integer representing the bit-flags for the field.
type The data type used for this field
decimals The number of decimals used (for integer fields)
*/
/// FIELD TYPE REFERENCE ///
/*
numerics
-------------
BIT: 16
TINYINT: 1
BOOL: 1
SMALLINT: 2
MEDIUMINT: 9
INTEGER: 3
BIGINT: 8
SERIAL: 8
FLOAT: 4
DOUBLE: 5
DECIMAL: 246
NUMERIC: 246
FIXED: 246
dates
------------
DATE: 10
DATETIME: 12
TIMESTAMP: 7
TIME: 11
YEAR: 13
strings & binary
------------
CHAR: 254
VARCHAR: 253
ENUM: 254
SET: 254
BINARY: 254
VARBINARY: 253
TINYBLOB: 252
BLOB: 252
MEDIUMBLOB: 252
TINYTEXT: 252
TEXT: 252
MEDIUMTEXT: 252
LONGTEXT: 252
*/
if($stmt = mysqli_prepare($db_link, $query))
{
// BIND PARAMETERS IF ANY //
if($params_size > 0)
{
call_user_func_array(array($stmt, 'bind_param'), makeValuesReferenced($params));
}
mysqli_stmt_execute($stmt);
$meta = mysqli_stmt_result_metadata($stmt);
$field_names = array();
$field_length = array();
$field_type = array();
$output_data = array();
/// THIS GET THE NAMES OF THE FIELDS AND ASSIGNS NEW VARIABLES USING THE FIELD NAME. THESE VARIABLES ARE THEN SET TO NULL ///
$count = 0;
while($field = mysqli_fetch_field($meta))
{
$field_names[$count] = $field->name;// field names
$var = $field->name;
$$var = null;
$field_names_variables[$var] = &$$var;// fields variables using the field name
$field_length[$var] = $field->length;// field length as defined in table
$field_type[$var] = $field->type;// field data type as defined in table (numeric return)
$count++;
}
setFieldLengthInfo($field_length);
setFieldTypesInfo($field_type);
$field_names_variables_size = sizeof($field_names_variables);
call_user_func_array(array($stmt, 'bind_result'), $field_names_variables);
$count = 0;
while(mysqli_stmt_fetch($stmt))
{
for($l = 0; $l < $field_names_variables_size; $l++)
{
$output_data[$count][$field_names[$l]] = $field_names_variables[$field_names[$l]];/// THIS SETS ALL OF THE FINAL DATA USING THE DYNAMICALLY CREATED VARIABLES ABOVE
}
$count++;
}
mysqli_stmt_close($stmt);
echo "<pre>";
print_r($output_data);
echo "</pre>";
}
function makeValuesReferenced($arr)
{
$refs = array();
foreach($arr as $key => $value)
$refs[$key] = &$arr[$key];
return $refs;
}
I've got a MySQL table with fields a1,a2,a3,b1,...,d1,d2, each field was declared as a BOOLEAN in the CREATE statement. (I also tried TINYINT(1) but had the same problem).
Then I have this PHP function which receives data from an HTML form:
public function add($a) {
$sql = "INSERT INTO property_classification
(a1,a2,a3,b1,b2,b3,b4,b5,b6,b7,b8,c1,c2,c3,d1,d2)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);";
// creating the classification_id
// e.g. "a1a2a3" => ["a1","a2","a3"]
$classifications = str_split($a['classifications'], 2);
$data = array();
// compile $data array
foreach (self::$classification_fields as $classification) {
// if user array contained any classification, set to true
if (in_array($classification, $classifications)) {
$data[$classification] = "1"; // I tried `true` too
} else {
$data[$classification] = "0"; // I tried `false` here
}
}
// set type for binding PDO params
foreach ($data as $key=>$value) settype($data[$key], 'int'); // tried 'bool'
$this->db->query($sql, $data);
$a['classification_id'] = $this->db->lastInsertId();
$this->log($a['classification_id']); // Output: "0"
...
The output should be a valid ID from 1+, but the insert failed so the lastInsertId() returned 0.
I checked what $sql compiled to, it came to this:
INSERT INTO property_classification (a1,a2,a3,b1,b2,b3,b4,b5,b6,b7,b8,c1,c2,c3,d1,d2) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);
I also output $data with the code: implode(",",$data); and it gave me this output:
1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0
Which was perfect because the input was "a1a2".
The only problem now is I don't understand why the query is failing all the time, because I put the two bits together like so:
INSERT INTO property_classification (a1,a2,a3,b1,b2,b3,b4,b5,b6,b7,b8,c1,c2,c3,d1,d2) VALUES(1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0);
Then I executed that query in MySQL Query Browser and it worked.
So why is it failing through PDO?
DBO class
function query($sql, $data) {
try {
$this->query = $this->db->prepare($sql);
if (!is_null($data) && is_array($data))
$this->query->execute($data);
else
$this->query->execute();
} catch (PDOException $e) {
array_push($this->log, $e->getMessage());
}
}
Since you're actually passing an associative array to the PDO, you can bind to named parameters. The use of ? or positional placeholders require a standard indexed array. If you're against using named params, just replace $data[$classification] = with $data[] =
Try the below.
public function add($a) {
$sql = "INSERT INTO property_classification
(a1,a2,a3,b1,b2,b3,b4,b5,b6,b7,b8,c1,c2,c3,d1,d2)
VALUES(:a1,:a2,:a3,:b1,:b2,:b3,:b4,:b5,:b6,:b7,:b8,:c1,:c2,:c3,:d1,:d2);";
// creating the classification_id
// e.g. "a1a2a3" => ["a1","a2","a3"]
$classifications = str_split($a['classifications'], 2);
$data = array();
// compile $data array
foreach (self::$classification_fields as $classification)
$data[$classification] = in_array($classification, $classifications) ? 1 : 0;
$this->db->query($sql, $data);
$a['classification_id'] = $this->db->lastInsertId();
$this->log($a['classification_id']); // Output: "0"
I'm trying to dynamically bind mysql_stmt parameters and get the result in an associative array. I've found this post here on Stack Overflow where Amber posted an answer with the following code:
Original post:
How to make a proper mysqli extension class with prepared statements?
"Assuming you're actually wanting to write your own version (as opposed to utilizing one of the existing libraries other answers have suggested - and those are good options, too)...
Here are a couple of functions which you may find it useful to examine. The first allows you to bind the results of a query to an associative array, and the second allows you to pass in two arrays, one an ordered array of keys and the other an associative array of data for those keys and have that data bound into a prepared statement:"
function stmt_bind_assoc (&$stmt, &$out) {
$data = mysqli_stmt_result_metadata($stmt);
$fields = array();
$out = array();
$fields[0] = $stmt;
$count = 1;
while($field = mysqli_fetch_field($data)) {
$fields[$count] = &$out[$field->name];
$count++;
}
call_user_func_array(mysqli_stmt_bind_result, $fields);
}
function stmt_bind_params($stmt, $fields, $data) {
// Dynamically build up the arguments for bind_param
$paramstr = '';
$params = array();
foreach($fields as $key)
{
if(is_float($data[$key]))
$paramstr .= 'd';
elseif(is_int($data[$key]))
$paramstr .= 'i';
else
$paramstr .= 's';
$params[] = $data[$key];
}
array_unshift($params, $stmt, $paramstr);
// and then call bind_param with the proper arguments
call_user_func_array('mysqli_stmt_bind_param', $params);
}
I tried studying the code to understand what it does and I've made the second function work properly but I don't know what I should do to be able to utilize the first function. How do I use it to retrieve an array similar to mysqli_result:: fetch_assoc()?
I want to be able to utilize the result in such a way like you used to do with:
while ($row = mysql_fetch_array($result)){
echo $row['foo']." ".$row['bar'];
}
Okay, here is a way to do it:
Edited, to fix bug when fetching multiple rows
$sql = "SELECT `first_name`,`last_name` FROM `users` WHERE `country` =? AND `state`=?";
$params = array('Australia','Victoria');
/*
In my real app the below code is wrapped up in a class
But this is just for example's sake.
You could easily throw it in a function or class
*/
// This will loop through params, and generate types. e.g. 'ss'
$types = '';
foreach($params as $param) {
if(is_int($param)) {
$types .= 'i'; //integer
} elseif (is_float($param)) {
$types .= 'd'; //double
} elseif (is_string($param)) {
$types .= 's'; //string
} else {
$types .= 'b'; //blob and unknown
}
}
array_unshift($params, $types);
// Start stmt
$query = $this->connection->stmt_init(); // $this->connection is the mysqli connection instance
if($query->prepare($sql)) {
// Bind Params
call_user_func_array(array($query,'bind_param'),$params);
$query->execute();
// Get metadata for field names
$meta = $query->result_metadata();
// initialise some empty arrays
$fields = $results = array();
// This is the tricky bit dynamically creating an array of variables to use
// to bind the results
while ($field = $meta->fetch_field()) {
$var = $field->name;
$$var = null;
$fields[$var] = &$$var;
}
$fieldCount = count($fieldNames);
// Bind Results
call_user_func_array(array($query,'bind_result'),$fields);
$i=0;
while ($query->fetch()){
for($l=0;$l<$fieldCount;$l++) $results[$i][$fieldNames[$l]] = $fields[$fieldNames[$l]];
$i++;
}
$query->close();
// And now we have a beautiful
// array of results, just like
//fetch_assoc
echo "<pre>";
print_r($results);
echo "</pre>";
}
The Answer from Emmanuel works fine, if only one row is selected! If the query select multiple rows, the $results-Array holds for every row a result, but the result is always filled with the last entry. With a little change in the fetch()-while it work well.
$sqlStmt is an string, filled with the mysql-query
$params is an array, filled with the variables that should passed
$results is an empty array, that holds the result
if (!is_string($sqlStmt) || empty($sqlStmt)) {
return false;
}
// initialise some empty arrays
$fields = array();
$results = array();
if ($stmt = $this->prepare($sqlStmt)) {
// bind params if they are set
if (!empty($params)) {
$types = '';
foreach($params as $param) {
// set param type
if (is_string($param)) {
$types .= 's'; // strings
} else if (is_int($param)) {
$types .= 'i'; // integer
} else if (is_float($param)) {
$types .= 'd'; // double
} else {
$types .= 'b'; // default: blob and unknown types
}
}
$bind_names[] = $types;
for ($i=0; $i<count($params);$i++) {
$bind_name = 'bind' . $i;
$$bind_name = $params[$i];
$bind_names[] = &$$bind_name;
}
call_user_func_array(array($stmt,'bind_param'),$bind_names);
}
// execute query
$stmt->execute();
// Get metadata for field names
$meta = $stmt->result_metadata();
// This is the tricky bit dynamically creating an array of variables to use
// to bind the results
while ($field = $meta->fetch_field()) {
$var = $field->name;
$$var = null;
$fields[$var] = &$$var;
}
// Bind Results
call_user_func_array(array($stmt,'bind_result'),$fields);
// Fetch Results
$i = 0;
while ($stmt->fetch()) {
$results[$i] = array();
foreach($fields as $k => $v)
$results[$i][$k] = $v;
$i++;
}
// close statement
$stmt->close();
}
Just to compare excellent answers from #Emmanuel and #matzino with the code you can get if choose PDO over mysqli:
$sql = "SELECT `first_name`,`last_name` FROM `users` WHERE `country` =? AND `state`=?";
$params = array('Australia','Victoria');
$stm = $query->prepare($sql);
$stm->execute($params);
$results = $stm->fetchAll(); // or fetch() or fetchColumn() depends on expected type
whoops, that's all?
After using the answer above I have figured out that there was some cleanup needed for myself, particularly the 'fieldNames[]' portion. The code below is in procedural style. I hope it will come of use to someone.
I cut the code from a class I made that can dynamically query data. There are a few things I removed to make it easier to read. In the class I have I allow the user to define definitions tables and foreign keys so that data entry on the front-end is restricted as well as filter and sort options for said related data. These are all parameters I removed as well as the automated query builder.
$query = "SELECT `first_name`,`last_name` FROM `users` WHERE `country` =? AND `state`=?";
$params = array('Australia','Victoria');
////////////// GENERATE PARAMETER TYPES IF ANY //////////////
// This will loop through parameters, and generate types. ex: 'ss'
$types = '';
$params_size = sizeof($params);
if($params_size > 0)
{
foreach($params as $param)
{
if(is_int($param))
{
$types .= 'i'; //integer
}else if(is_float($param))
{
$types .= 'd'; //double
}else if(is_string($param))
{
$types .= 's'; //string
}else
{
$types .= 'b'; //blob and unknown
}
}
array_unshift($params, $types);
}
////////////////////////////////////////////////////////////
// This is the tricky part to dynamically create an array of
// variables to use to bind the results
//below from http://php.net/manual/en/mysqli-result.fetch-field.php
/*
name The name of the column
orgname Original column name if an alias was specified
table The name of the table this field belongs to (if not calculated)
orgtable Original table name if an alias was specified
def Reserved for default value, currently always ""
db Database (since PHP 5.3.6)
catalog The catalog name, always "def" (since PHP 5.3.6)
max_length The maximum width of the field for the result set.
length The width of the field, as specified in the table definition.
charsetnr The character set number for the field.
flags An integer representing the bit-flags for the field.
type The data type used for this field
decimals The number of decimals used (for integer fields)
*/
/// FIELD TYPE REFERENCE ///
/*
numerics
-------------
BIT: 16
TINYINT: 1
BOOL: 1
SMALLINT: 2
MEDIUMINT: 9
INTEGER: 3
BIGINT: 8
SERIAL: 8
FLOAT: 4
DOUBLE: 5
DECIMAL: 246
NUMERIC: 246
FIXED: 246
dates
------------
DATE: 10
DATETIME: 12
TIMESTAMP: 7
TIME: 11
YEAR: 13
strings & binary
------------
CHAR: 254
VARCHAR: 253
ENUM: 254
SET: 254
BINARY: 254
VARBINARY: 253
TINYBLOB: 252
BLOB: 252
MEDIUMBLOB: 252
TINYTEXT: 252
TEXT: 252
MEDIUMTEXT: 252
LONGTEXT: 252
*/
if($stmt = mysqli_prepare($db_link, $query))
{
// BIND PARAMETERS IF ANY //
if($params_size > 0)
{
call_user_func_array(array($stmt, 'bind_param'), makeValuesReferenced($params));
}
mysqli_stmt_execute($stmt);
$meta = mysqli_stmt_result_metadata($stmt);
$field_names = array();
$field_length = array();
$field_type = array();
$output_data = array();
/// THIS GET THE NAMES OF THE FIELDS AND ASSIGNS NEW VARIABLES USING THE FIELD NAME. THESE VARIABLES ARE THEN SET TO NULL ///
$count = 0;
while($field = mysqli_fetch_field($meta))
{
$field_names[$count] = $field->name;// field names
$var = $field->name;
$$var = null;
$field_names_variables[$var] = &$$var;// fields variables using the field name
$field_length[$var] = $field->length;// field length as defined in table
$field_type[$var] = $field->type;// field data type as defined in table (numeric return)
$count++;
}
setFieldLengthInfo($field_length);
setFieldTypesInfo($field_type);
$field_names_variables_size = sizeof($field_names_variables);
call_user_func_array(array($stmt, 'bind_result'), $field_names_variables);
$count = 0;
while(mysqli_stmt_fetch($stmt))
{
for($l = 0; $l < $field_names_variables_size; $l++)
{
$output_data[$count][$field_names[$l]] = $field_names_variables[$field_names[$l]];/// THIS SETS ALL OF THE FINAL DATA USING THE DYNAMICALLY CREATED VARIABLES ABOVE
}
$count++;
}
mysqli_stmt_close($stmt);
echo "<pre>";
print_r($output_data);
echo "</pre>";
}
function makeValuesReferenced($arr)
{
$refs = array();
foreach($arr as $key => $value)
$refs[$key] = &$arr[$key];
return $refs;
}