Handling dynamic number of answers in prepared statement - php

on the frontend I am using JQuery Validate, and I pass the following to the backend
data: {
'field1': $("input[name='field1']:checked").val(),
'field2': $("input[name='field2']:checked").val(),
'field3': $("#field3").val(),
'field4' : $("#field4").val(),
'field5' : $("#field5").val(),
'field6' : $("#field6").val()
}
The first three fields are required, so they will always have a value. The next three are optional, so they may not have a value. In my PHP file, I do something like this for required fields
if (!empty($_POST["field1"])) {
$field1 = filter_var($_POST["field1"], FILTER_SANITIZE_STRING);
array_push($inputArray, $field1);
} else{
$errors['field1'] = 'Please select field1';
}
And for optional fields I do
if (!empty($_POST['field4'])) {
$field4 = filter_var($_POST["field4"], FILTER_SANITIZE_STRING);
array_push($inputArray, $field4);
}
By the end of this, I have an $inputArray which may contain between 3-6 values which is passed to my database file. Here, I am doing something like this
$stmt = $dbh->prepare("INSERT INTO database_table(Field1, Field2, Field3, Field4, Field5, Field6) VALUES (?, ?, ?, ?, ?, ?)");
$stmt->bindParam(1, $this->inputArray[0]);
Now that will be fine for the first three, but if I then try an optional element and its not there, an error will be thrown.
Whats the best way to handle this type of situation? In the PHP file, should I always push an empty value for the three if statements that are optional fields e.g.
else {
array_push($inputArray, '');
}
I know off several solutions I could potentially use, just wanted to get opinions from others as to how they would handle it.
Thanks

I've found that the best way of handling this sort of problem is to dynamically build the query. This sort of approach is easier when you use an associative $inputArray. As such, instead of doing
array_push($inputArray, $field1);
Do
$inputArray['field1Name'] = $field1;
replacing "field1" with the appropriate value for each field.
That way you can build your query like this:
$qry = "INSERT INTO database_table(";
$qry .= implode(',', array_keys($inputArray)); //append a comma separated list of field names.
$qry .= ") VALUES("
$qry .= trim(str_repeat('?,', count($inputArray)), ','); //append ?, for each element in the array and trim the trailing comma
$qry .= ')';
$stmt = $dbh->prepare($qry);
$stmt->execute( array_values($inputArray)); //Execute the query with the values from the input array
In this way the number of arguments in the sql query is dynamic and based on the number of fields that were filled out.
This could be easily changed to use named parameters instead of ? but the general concept is the same.

Related

PHP Prepared Statement - Dynamic Vars Number of Element Error

My previous question was closed because they said it was a duplicate but the duplicate posts did not answer my question. So here I go again and I put some additional comments in the edit section to state why the duplicate posts did not help me.
I am trying to construct a prepared statement dynamically and I keep getting the following error:
mysqli_stmt_bind_param(): Number of elements in type definition string
doesn't match number of bind variables in
When I echo my statements the number of type definitions matches the bind variable so I don't know what is wrong. I think my code may be passing in strings, quotes or something instead of variables but I'm new to prepared statement and not sure how to check my query. When using simple mysqli_query I can echo the query and see were my error is at. I'm not sure how to do this with prepared statements so I'm hoping someone can help uncover my error.
I am trying to construct the prepares statement dynamically so that I can reuse the code as follows:
$db = mysqli_stmt_init($dbconnection);
// I have looped through my fields and constructed a string that when
// echoed returns this:
// ?, ?, ?, ?,
// I use sub str just to remove the last comma and space leaving me
// with the string
// ?, ?, ?, ?.
// Ive echoed this to the browser to make sure it is correct.
$preparedQs = substr($preparedQs, 0, -2);
// I then loop through each field using their datatype and constructs
// the type string as follows ssss. Ive echoed this to the browser to
// make sure it is correct.
$preparedType = 'ssss';
// I then loop through my post array verifying and cleaning the data
// and then it constructing a string of clean values that results in
// Mike, null, Smith, Sr., (First, Middle, Last, Suffix) I use substr
// again just to remove the last comma and space. Ive echoed this to
// the browser to make sure it is correct.
$cleanstr = substr($cleanstr, 0, -2);
// I then explode that string into a an array that I can loop through
// and assign/bind each value to a variable as follows and use substr
// again to remove last comma and space.
$cleanstr = explode(", ", $cleanstr);
$ct2 = 0;
foreach ( $cleanstr as $cl){
$name = "a".$ct2;
$$name = $cl;
$varstr .= "$".$name.", ";
$ct2 = $ct2 +1;
}
$varstr = substr($varstr, 0, -2);
// I've echoed the $varstr to the browser and get $a1, $a2, $a3, $a4.
// I have also echo their value outside of the loop and know values
// have been assigned.
// I then try to assign each step above the appropriate
// prepared statement place holder
$stmt = mysqli_stmt_prepare($db, "INSERT INTO Contacts VALUES (". $preparedQs. ")");
mysqli_stmt_bind_param($db, "'".$preparedType."'", $varstr);
mysqli_stmt_execute($stmt);
I'm am not sure what I am doing wrong because when I echo $preparedQs, $preparedType and $varstr they all have the same number of elements yet I'm getting the "mysqli_stmt_bind_param(): Number of elements in type definition string doesn't match number of bind variables in.." error. All i can think is that I have quotes or something where I shouldn't but I've tried adding and removing quotes in certain areas and cant get the error to resolve.
Also, I read some posts about passing null in prepared statement but even when I replace the null with an actual value, I still get the same error.
It's probably worth noting that when using simple procedural mysqli_query and mysqli_real_escape_string to clean my data things work fine. I am trying to improve my security by converting my application to prepared statement simply for the added security.
This question is different for two reasons
I am using procedural coding and not object or PDO. So being new to prepared statements, the examples given aren't helpful even after trying to make sense of them.
I am using an insert statement, not a select or update statement which in procedural php the query string is written differently for insert than for select or update statements.
//UPDATED CODE
global $dbconnection;
if(!$dbconnection){
die("Function wm_dynamicForm connection failed.</br>");
} else {
//echo "</br>Function wm_connectionToDatabase connection success</br>";
}
$db = mysqli_stmt_init($dbconnection);
$preparedQs = substr($preparedQs, 0, -2); //removes the end , from my string
$cleanstr = substr($cleanstr, 0, -2); //removes the end , from my string
$cleanstr = explode(", ", $cleanstr);
$ct = 0;
foreach ( $cleanstr as $cl){
$items[] = array(
'a'.$ct => $cl,
);
$ct = $ct + 1;
}
$stmt = mysqli_stmt_prepare($db, "INSERT INTO Contacts VALUES (". $preparedQs. ")");
mysqli_stmt_bind_param($db, $preparedType, ...$items);
mysqli_stmt_execute($stmt);
if(!mysqli_stmt_execute($stmt)){
echo "Error: ".mysqli_error($db);
}
You could do dynamic bind with php 5.6 feature called unpacking operator/elipsies the ....
$db = mysqli_connect('localhost', 'root', 'pass', 'database');
$data = array('name' => 'foo', 'age' => 99, 'email' => 'abc#abc.com');
$stmt = mysqli_stmt_prepare($db, "INSERT INTO Contacts VALUES (". $preparedQs. ")");
mysqli_stmt_bind_param($db, $preparedType, ...$data);
mysqli_stmt_execute($stmt);
I've been here before, dynamic prepared statement, dynamic query preparation.
The problem is not your code so far, the problem is the array of your sql fields you dynamically prepared to bind.
The index of that array starts with zero(0), but the index of your bindValue needs to start with one(1).
So what you will do is to make your field array index to start with 1.
In php you can force defaul index of an array to start with 1 instead of zero.
If am not wrong you have:
dbfield="username, password, name"
dbvalue="?, ?, ?"
and you have an array of input value you are looping with like:
foreach($inputarray as $key=>$value){
// key index must start from 1
//now you can bind
bindValue($key, $value);
}
If am flowing hit me answer accept.
try to use like this in prepared statement.
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
$conn = new mysqli($servername, $username, $password, $dbname);
$cleanstr = "John,Dew,Doe,Sr.";
$cleanstr = explode(",", $cleanstr);
$varstr=array();
foreach($cleanstr as $cl){
$varstr[] = "$".$cl;
}
$operation = "INSERT INTO Contacts (firstname, middlename, lastname, suffix) VALUES (?, ?, ?, ?)";
$callfunc = insertCommon($conn,$varstr, $operation);
function insertCommon($conn,$varstr, $operation){
$types = "";
foreach($varstr as $value)
$types .= "s";
$varstr = array_merge(array($types),$varstr);
$insertQry = $conn->prepare($operation);
$refArray = array();
foreach($varstr as $key => $value) $refArray[$key] = &$varstr[$key];
call_user_func_array(array($insertQry, 'bind_param'), $refArray);
$insertQry->execute();
return true;
}

Error:sqlstate[hy093]: invalid parameter number

I can convert the echo'ed output in to an SQL statement that executes in phpMyAdmin going...
From this:
INSERT INTO crumbs (ip_address,ip_address_2,device_info,user_id,connections) VALUES(?,?,?,?,?)Value:'00.000.000.000', '00.000.000.000', 0,0000, 1
Into this:
INSERT INTO crumbs (ip_address,ip_address_2,device_info,user_id,connections) VALUES('00.000.000.000', '00.000.000.000', 0,0000, 1)
It inserts the data in to the DB, no errors, however it executes through PHP-PDO...
With:
SQLSTATE[HY093]: Invalid parameter number
The code:
$columns = '('.implode(',', array_keys($user_connection)).''.",user_id,connections)";
$inserts="(".implode(',',array_fill(0,count($user_connection)+2, '?')).")";
$values = implode(', ',($user_connection)).",$user_id, 1";
$sql_insert = "INSERT INTO crumbs ".$columns." VALUES".$inserts;
$stmt = $this->_db->prepare($sql_insert);
$stmt->execute(array($values));
Edit-Adding $user_connection
$user_connection [ 'ip_address'] = "'".$_SERVER['REMOTE_ADDR']."'";
$user_connection [ 'ip_address_2']="'".$_SERVER['HTTP_X_FORWARDED_FOR']."'";
$user_connection ['device_info']=0;
The error occurs during the execution of the SQL code. I've gone over all the examples and found nothing that's equivalent, I'm thinking it's something simple I'm missing (a rule?) since the code executes locally.
You have to do something like this:
// ..code..
$values = $user_connection;
$values[] = $user_id;
$values[] = 1;
// ..code..
$stmt->execute($values);
Explanation of the problem:
When you have multiple ? placeholders, you can pass each value to be bounded as the values of an array (See Example #3 from the manual).
Now, since you are using implode, $values will be a single string, something like
'192.168.0.1', '8.8.8.8', 0, 'userid', 1
That means that when you call execute(array($values)), it will, in fact, bound it like this (representation-only, it's not really like this)
INSERT INTO crumbs (ip_address,ip_address_2,device_info,user_id,connections) VALUES ("'192.168.0.1', '8.8.8.8', 0, 'userid', 1", ?, ?, ?, ?)
because you only sent and array that has one value: the implosion of the other array. Since you didn't provide the same amount of values (1) as you have placeholders (5), you end up with
Invalid parameter number

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

PDO Insert Array Using Key As Column Name

I am inserting the $_POST contents of my PHP array into a table with PDO. I was looking at the following lines of code and I had one of those "there has to be a better way to do this" moments. If the key name matches the column name in the table, is there a more simple way to insert all of it?
Code for example:
$statement = $db->prepare("INSERT INTO `applications`(`username`, `email`, `password`, `name`) VALUES (?,?,?,?)");
$statement->execute(array($_POST['username'], $_POST['email'],$_POST['password'],$_POST['name']));
This code WORKS but it just seems a bit over-the-top (especially as more and more columns are added).
I would do it this way:
Declare the columns first. We'll use these to extract a subset of $_POST for use as columns. Otherwise a user could pass bogus request parameters that don't match any columns of the table, which would break our SQL.
$columns = array('username','email','password','name');
$column_list = join(',', $columns);
Create named parameter placeholders i.e. :username.
$param_list = join(',', array_map(function($col) { return ":$col"; }, $columns));
Form the SQL separately, because it's easier to read and debug if it's in its own variable.
$sql = "INSERT INTO `applications` ($column_list) VALUES ($param_list)";
Always check for error status returned from prepare() and execute().
$statement = $db->prepare($sql);
if ($statement === false) {
die(print_r($db->errorInfo(), true));
}
Here we take only the fields of $_POST that match the columns we want to insert.
$param_values = array_intersect_key($_POST, array_flip($columns));
And pass that array to execute(). Again, check for error return status.
$status = $statement->execute($param_values);
if ($status === false) {
die(print_r($statement->errorInfo(), true));
}

PDO unexpectedly throws bound variable errors with multiple bound parameters

I have a PDO prepared statement in which the bound variables are prepared dynamically (they can vary from call to call) in an advanced search function on our site.
I know the actual SQL call is correct but for some reason I am getting the following error when trying to pass my string variable into the prepared statement:
SQLSTATE[HY093]: Invalid parameter
number: number of bound variables does
not match number of tokens
I have had this error before and am very familiar with the normal resolution steps. However, my circumstances are quite strange. With the following sample code:
$columns = "FirstName, LastName, ID, City, State";
$sWhere = "WHERE (FirstName LIKE ? AND LastName
LIKE ? AND ID LIKE ? AND City
LIKE ? AND State LIKE ?)";
$sVal = "'tom', 'lastname', '12345', 'Diego', 'CA'";
$sql = "SELECT ".$columns." FROM table ".$sWhere;
$stmt = $db->prepare($sql);
$stmt->execute(array($sVal));
where $sVal can range from 'firstname', 'lastname'.... to over 12 variables. Changing the number of variables has the same result. The complete statement is:
SELECT FirstName, LastName, ID, City, State
FROM table
WHERE (FirstName LIKE ? AND LastName
LIKE ? AND ID LIKE ? AND City
LIKE ? AND State LIKE ?)
When I run my query as is, the error above is returned. When I thought I did in fact have an incorrect number of variables, I ran an ECHO on my $value statement and found they did match.
As a secondary test, I took the output from the echo of $value and plugged directly back into the execute array:
$stmt->execute(array('tom', 'lastname', '12345', 'Diego', 'CA'));
This works with any issue at all.
It does not affect my question but I also placed % symbols within my $sVal variable for correctness:
$sVal="'%tom%', '%lastname%', '%12345%', '%Diego%', '%CA%'";
It makes ZERO sense to me that the echo'd output of the SAME variable would work but the variable itself would not. Any ideas?
Your $sVal is not an array, it's just a simple string, so when you write array($sVal), the execute() sees only one value.
You need to explode() your $sVal string to become an array:
// clean up the unnecessary single quotes and spaces
$value = str_replace(array("'", ", "), array("", ","), $value);
// make the array of the values
$value = explode(',', $value);
$stmt->execute($value);
The problem is that execute accepts an array of parameters, with each parameter having its own key. Passing a SQL-like, comma-separated string will not work, and even if it did, it would render PDO useless.
This is wrong:
$sVal = "'tom', 'lastname', '12345', 'Diego', 'CA'";
This is how it is supposed to be done:
$sVal = array('tom', 'lastname', '12345', 'Diego', 'CA');
Per example, if you are receiving data from a form in POST, it would be:
$sVal = array(
$_POST['firstname'],
$_POST['lastname'],
$_POST['zipcode'],
$_POST['city'],
$_POST['state'],
);
$stmt->execute($sVal);

Categories