MySQLi "bind_param" in cycle - php

Why can I not use "bind_param" like this? Are there any alternative ways to use Binding in a cycle?
$insert = $this->db->prepare('INSERT INTO '.$tableName.' ('.implode($colum, ', ').') VALUES ('.implode($placeholder, ', ').'); ');
for ($i=0;$i<$count;$i++) {
$insert->bind_param($query[$i]['type'], $query[$i]['value']);
}

Well, your error makes it pretty clear: your $placeholder array doesn't contain the same number of placeholders as you have parameters in your $query array.
Check the code building the $placeholder and $query arrays. If you can't find the problem, add that piece of code in your question.
Ok, sorry, I'm not used to mysqli. Apparently you have to pass all the parameters in one call to bind_param. That's annoying, but there's a workaround.
The call_user_func_array function allows you to pass the arguments to a function as an array.
So you can:
construct the string of types by looping through the parameters;
make an array $params with that string at index 0, and the parameters' values at subsequent indexes;
call call_user_func_array(array($insert, 'bind_param'), $params);.
That would look like this:
$insert = $this->db->prepare('INSERT INTO '.$tableName.' ('.implode($colum, ', ').') VALUES ('.implode($placeholder, ', ').'); ');
$values = array();
for ($i=0 ; $i<$count ; $i++) {
$types .= $query[$i]['type']; // this needs to be one single character from [idsb]
$values[] = $query[$i]['value'];
}
$params = array_merge(array($types), $values);
call_user_func_array(array($insert, 'bind_param'), $params);

Related

Mysqli prepared statements build INSERT query dynamically from array

I'm trying to develop my functions in PHP (not OOP), to create a CRUD. The goal is to use the same function to any table, but I got stuck already in the first one. Can't figure how to do this.
What I have right now:
// function to avoid injections
function validate($link, $field){
$valid = mysqli_real_escape_string($link, $field);
$valid = strip_tags($valid);
return $valid;
}
// validate input of array
function sqlWithArray($link,$array){
$return = array();
foreach($array as $field=>$val){
$return[$field] = "'".validate($link, $val)."'";
}
return $return;
}
// Multi insert to any table
function InsertDB($link, $table, array $args){
$rows = sqlWithArray($link,$args);
$keys = "(".implode(array_keys($args)," ,").")";
$values = " VALUES (".implode(array_values($args),", ").")";
$query = "INSERT INTO $table $keys $values";
return $link->execute();
}
I was try to using it as:
InsertDB($link, "test_table", $args); //$args is an array
But I keep getting the following error:
PHP Fatal error: Uncaught Error: Call to undefined method mysqli::execute() in includes\functions.php:37
My 37 line is empty, but 36 and 38 are the following:
$query = "INSERT INTO $table $keys $values";
return $link->execute();
What I'm doing wrong here?
Having such a function is a good idea per se. It indicates that you are a programmer in your heart, not just a tinkerer that writes PHP from ready made blocks like a Lego figure. Such a function can greatly improve your code.
But with great power comes great responsibility. Such a function is a constant danger of SQL injection, through table and field names. You should take care of that. Not to mention it should be properly implemented using prepared statements for the data.
First of all, you will need a general purpose function to execute an arbitrary MySQL query using a query and an array of parameters. I have a simple mysqli helper function for you. It will be a basic function to execute all prepared queries:
function prepared_query($mysqli, $sql, $params, $types = "")
{
$types = $types ?: str_repeat("s", count($params));
$stmt = $mysqli->prepare($sql);
$stmt->bind_param($types, ...$params);
$stmt->execute();
return $stmt;
}
Now we can start constructing the SQL query dynamically. For this we will need a function that would escape identifiers
function escape_mysql_identifier($field){
return "`".str_replace("`", "``", $field)."`";
}
It will make identifiers safe, at least as long as you are using Unocode.
Now we can proceed to creation of the correct SQL string. We will need to create an SQL with placeholders, like this:
INSERT INTO `staff` (`name`,`occupation`) VALUES (?,?)
So let's write a function that would create a query like this
function create_insert_query($table, $keys)
{
$keys = array_map('escape_mysql_identifier', $keys);
$fields = implode(",", $keys);
$table = escape_mysql_identifier($table);
$placeholders = str_repeat('?,', count($keys) - 1) . '?';
return "INSERT INTO $table ($fields) VALUES ($placeholders)";
}
And finally we can write the long-sought crud function:
function crud_insert($conn, $table, $data) {
$sql = create_insert_query($table, array_keys($data));
prepared_query($conn, $sql, array_values($data));
}
called like this
$args = ['name' => "D'Artagnan", "occupation" => 'musketeer'];
crud_insert($link, "test_table", $args);

Problems when binding values

I am working for the first time with prepared statements but I got stuck at this error. For some reason I cant pass the bind types as a parameter?
My code:
function insert($table, $columns = array(), $bindTypes, $values = array()) {
// Store connection.
$connection = connection();
$columnValues = null;
$index = 1;
// Prepare unassigned value string.
foreach ($columns as $column) {
$columnValues .= '?';
if ($index < count($columns)) {
$columnValues .= ', ';
}
$index++;
}
// Debugg purpose: echo query example:
echo "INSERT INTO {$table} (" . implode(', ', $columns) . ") VALUES ({$columnValues})";
// Prepare statement.
$statement = $connection->prepare("INSERT INTO {$table} (" . implode(', ', $columns) . ") VALUES ({$columnValues})");
$statement->bind_param($bindTypes, implode(', ', $values));
}
insert('test', array('name'), 'i', array(1));
If I echo the query example I get "INSERT INTO test (name) VALUES (?)".
Please spare me I am still a learning noob.
PHP > 5.6 version:
function insert($connection, $table, $columns, $values) {
$columnStr = "`".implode("`,`",$columns);
$valueStr = str_repeat('?,', count($values) - 1) . '?';
$types = str_repeat('s', count($values));
$statement = $connection->prepare("INSERT INTO `$table` ($columnStr) VALUES ($valueStr)");
$statement->bind_param($types, ...$values);
$statement->execute();
}
insert($conn, 'test', ['name'], [1]);
Note that you should never ever take table or column names out of user input but always have them hard-coded in your script. Which makes a distinct function for the insert quite useless.
Let's look at the docs:
bool mysqli_stmt::bind_param ( string $types , mixed &$var1 [, mixed &$... ] )
In other words, first argument determines data types and you pass the values as individual parameters starting from the second parameter. However you have this:
$statement->bind_param($bindTypes, implode(', ', $values));
You're combining all individual values into a single comma-separated string, which doesn't make the least sense, esp. if you consider that the function expects arguments by reference.
I see you've flagged your post with MySQLi, which I'm pretty sure is the problem here.
Instead I'd go with PDO on this one, as it allows for a variable number of parameters in a much simpler manner. Allowing you do do something quite similar to example 5 from the PHP manual.

Using bind for form with lot of inputs (PHP)

I have form with lot of inputs, and I'm trying to import them in database (mysql).
I want to use bind but trying to avoid writing all variables so many times. Probably I can't explain so good, so I will here is a code
if(isset($_POST['firstName']) && isset($_POST['lastName']) && isset($_POST['gender'])){
$firstName=trim($_POST['firstName']);
$lastName=trim($_POST['lastName']);
$gender=trim($_POST['gender']);
if(!empty($firstName)&& !empty($lastName)) {
$unos = $db->prepare("INSERT INTO members (firstName,lastName,gender) VALUES (?,?,?)");
$unos->bind_param('sss', $firstName, $lastName, $gender);
if($unos->execute()) {....
1.Well this is working fine , and it's not a problem, but now I want to add more inputs so I tried this
if(isset($_POST['firstName']) && isset($_POST['lastName']) && isset($_POST['gender'])){
$firstName=trim($_POST['firstName']);
$lastName=trim($_POST['lastName']);
$gender=trim($_POST['gender']);
$param=array('$firstName','$lastName','$gender');
$type='sss';
$param_list = implode(',', $param);
if(!empty($param)) {
$unos = $db->prepare("INSERT INTO members (firstName,lastName,gender) VALUES (?,?,?)");
$unos->bind_param($type,implode(',', $param));
if($unos->execute()) {....
and it's not working. I get "Number of elements in type definition string doesn't match number of bind variables"...
I don't get it, because when I echo this implode thing I get what I need.
I'm pretty newbie with PHP, so help will be so precious. :)
You can try this:
if(isset($_POST['firstName']) && isset($_POST['lastName']) && isset($_POST['gender'])){
$firstName=trim($_POST['firstName']);
$lastName=trim($_POST['lastName']);
$gender=trim($_POST['gender']);
$param=array('firstName' => 's','lastName' => 's','gender' => 's');
if(!empty($param)) {
$unos = $db->prepare("INSERT INTO members (". implode(',', array_keys($param) .") VALUES (". implode(',', array_fill(0, count($param), '?')) .")");
foreach($param as $paramName => $paramType) {
$unos->bind_param($paramType, $paramName);
}
if($unos->execute()) {....
You can pus as many parameters to $param array. Key should the name of the db column, value is its type.
You will need a variable for each question mark, but you will also need to bind each of the parameters separately. In your current situation, you bind a comma-separated list of values as a single string parameter.
What about this? I attempted to make the entire code rely on a single array of fields. If you want extra fields, you can just add them to the array and the rest of the code should respond to it. I don't have a proper test environment at hand and I typed this code by heart, so sorry for any typos. :)
// The fixes list of allowed/expected fields. Other values are ignored.
$fields = array('firstname', 'lastname', 'gender');
// Check if each value exists, and put them in an array.
$paramvalues = array();
foreach ($fields as $field) do
{
if (!isset($_POST[$field]))
die("missing field $field");
$paramvalues[] = & $_POST[$field]; // Bind_param wants a ref value, hence `&`
}
// Build a list of fields for the dynamic query.
$fieldlist = implode($fields, ',');
// And a list of placeholders.
$paramlist = implode(array_fill(0, count($fields), '?'), ',');
// And a list of types, assuming all parameters are strings.
$paramtypes = str_pad('', count($fields), 's');
// Prepare the query
$unos = $db->prepare("INSERT INTO members ($fieldlist) VALUES ($paramlist)");
// Build an array of reference values to be passed to call_user_func_array:
$paramrefvalues = array();
$paramrefvalues[] = $paramtypes
foreach ($paramvalues as $value) do
{
$paramrefvalues[] = & $value;
}
// Call bind_param using this array of by-ref parameters
call_user_func_array(array($unos, 'bind_param'), $paramrefvalues);
This code is loosely based on this article

create PHP function for PDO insert query

I have tried to create a function for an SQL/PDO Insert query:
function InsertQuery ($table,$cols,$values) {
global $pdo_conn;
foreach($values as $values2) {
$values2 = $values2;
}
$stmt='INSERT into $table (';
foreach($cols as $cols2) {
$stmt.=" ".$cols2.", ";
}
$stmt.=" ) VALUES ( ";
foreach($cols as $cols2) {
$stmt.=" :".$cols2." ";
}
$stmt.=" ) ";
$stmt2 = $pdo_conn->prepare($stmt);
foreach($cols as $cols2) {
$stmt2->bindParam(':$cols2', $cols2);
}
}
but i am getting the error:
Catchable fatal error: Object of class PDOStatement could not be converted to string in /home/integra/public_html/admin/includes/functions.php on line 30
please be patient with me as i am new to PDO and just used to using MySQL
have i put the prepared statement wrong or my foreach loops?
I believe the statement should look like:
$stmt2 = $pdo_conn->prepare('INSERT into $table (col1) values (:val1)');
$stmt2->bindParam(':$val1', $val);
here is how i called my function:
$col=array('col1');
$val=array('val1');
InsertQuery ("table1",$col,$val);
UPDATE:
Ok here is my new code:
global $pdo_conn;
foreach($values as $values2) {
$values2 = $values2;
}
$stmt='INSERT into '.$table.' (';
foreach($cols as $cols2) {
$stmt.=" ".implode(",", $cols2)." ";
}
$stmt.=" ) VALUES ( ";
foreach($cols as $cols2) {
$stmt.=" :".implode(",", $cols2)." ";
}
$stmt.=" ) ";
$stmt2 = $pdo_conn->prepare($stmt);
foreach($cols as $cols2) {
$stmt2->bindParam(':$cols2', $cols2);
}
but i now get the error about the implode:
Warning: implode() [function.implode]: Invalid arguments passed in /home/integra/public_html/admin/includes/functions.php on line 18
Warning: implode() [function.implode]: Invalid arguments passed in /home/integra/public_html/admin/includes/functions.php on line 22
which i think is because there is nothing to implode as there is only one column and one value
Use type hints to ensure the function arguments are arrays:
function InsertQuery ($table, array $cols, array $values) {
Make sure your PDO connection is accessible. If it's global, you have to declare it (credit to #u_mulder):
global $pdo_conn;
The following does nothing, get rid of it:
foreach($values as $values2) {
$values2 = $values2;
}
Use builtin array functions instead of foreach'ing everything:
$col_list = implode(",", $cols);
$param_list = implode(",", array_fill(1,count($cols), "?"));
Variables don't expand inside single-quotes. You need to use double-quotes (credit to #MichaelBerkowski).
Also, use $stmt for a PDOStatement object, and not for the SQL string. That's confusing.
$sql="INSERT into $table ($col_list) VALUES ($param_list)";
$stmt = $pdo_conn->prepare($sql);
You don't need to write a foreach loop to bindParam() in PDO. You can just pass an array of values to execute(). And you already have the values in an array, so it's really easy:
$stmt->execute($values);
}
For extra safety, make sure to delimit the columns, in case someone uses special characters or a SQL keyword in a column name:
$col_list = implode(",", array_map(function ($c) { return "`$c`" }, $cols));
And make sure the values is in a simple array, not an associative array:
$stmt->execute(array_values($values));
Re your comment:
would you be able to show me how to do the same with select, I'm not sure how it would work as if i have a where clause what would i do with it in the function?
One could for example design a function with an argument $where that is an associative array, whose keys are column names, and whose values are the values you're searching for.
Assume the resulting WHERE clause includes these column/value pairs as AND terms, and all the comparisons are equality.
function SelectQuery($table, array $where) {
global $pdo_conn;
$sql = "SELECT * FROM `$table` ";
$values = null;
if ($where) {
$sql .= "WHERE " . implode(" AND ",
array_map(function ($c) { return "`$c` = ?"; } array_keys($where)));
$values = array_values($where);
}
$stmt = $pdo_con->prepare($sql);
$stmt->execute($values);
}
Of course this supports only a small subset of the possible expressions you can have in a SELECT, but I'm just demonstrating a technique here.
If you want a more fully-feature query builder for PHP, take a look at Zend_Db_Sql or Doctrine QueryBuilder or Laravel query builder.
if anything changes on my server and the PDO stops working i can revert back to MySQL while i fix it.
PDO has been stable since 2005 and it will not stop working, unless you change your PHP environment and disable the extension or the mysql driver or something.
Whereas the ext/mysql extension will stop working. It is currently deprecated and PHP has announced they will remove it in a future version of PHP.
There are a few things going on:
First, $cols and $vals should be arrays, but they are strings.
Quick fix is to make them arrays:
$col = array('col1');
$val = array('val1');
InsertQuery("table1", $col, $val);
Second, $pdo_conn is unknown in the function scope. Make it a parameter or a global.
you can also use this for create query from array:
$myArray = array(
'col1' => 'val1',
'col2' => 'val2'
);
$query = "INSERT INTO table (" . implode(", ", array_keys($myArray)) . ") VALUES (" . implode(", ", $myArray) . ")";
maybe usefull for you
http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers

build prepared statement from array and pass variable to execute

How to pass variable in loop to execute ???
example from one answer here...
$placeholders = array_fill(0, count($array), '?');
$keys = $values = array();
foreach($array as $k => $v) {
$keys[] = $k;
$values[] = !empty($v) ? $v : null;
}
$stmt = $mysqli->stmt_init();
$query = 'INSERT INTO `'.DB_TABLE_PAGES.'` '.
'('.implode(',', $keys).') VALUES '.
'('.implode(',', $placeholders).')';
$stmt->prepare($query);
call_user_func_array(
array($stmt, 'bind_param'),
array_merge(
array(str_repeat('s', count($values))),
$values
)
);
$stmt->execute();
but what about multiple array. I want add to db 10000 values but not build and bind statement every pass..
Is it possible ?
So I want build statement from array, bind params (i don't know how). Than in loop pass variable (identificated by key) and execute...
something universal if I don't wont write statement for every table (just make array of column names and variables)
When using prepared statements and mysqli all you need to do is change the values stored in our bound parameters and run execute a second time. This is the point of bound parameters, to allow multiple execution of the statement without the overhead of re-sending the query (also a great security plus by nature but that is beside the point.)
Take for example:
$param1 = '';
$param2 = '';
$param3 = '';
$param4 = '';
$query = 'INSERT INTO table VALUES (?, ?, ?, ?)';
$format = 'ssss';
$params = array(&$param1, &$param2, &$param3, &$param4);
$stmt = $mysqli->stmt_init();
$stmt->prepare($query);
$params = array_merge(array($format), $params); #set up format and parameters for binding
call_user_func_array(array($stmt, 'bind_param'), $params); #parameters specified so bind them
foreach($data as $data_point){
$param1 = $data_point[0];
$param2 = $data_point[1];
$param3 = $data_point[2];
$param4 = $data_point[3];
$stmt->execute();
}
This will prepare your statement and then loop through the data stored in $data taking each of the values, putting it into your prepared parameters and then execute the statement with the new parameters.
Mileage will vary on this particular code because it doesn't do any checking on the sql error statement and it may be much more efficient to do several rows in one insert for many applications.

Categories