My code -
$con = new PDO ('mysql:host=localhost;dbname=air','root','123456');
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$fields = implode(", ", $fields);
echo $fields;
$values = implode("','", $values);
echo $values;
// have to make this prevent sql injection //
// it wont work if i added bindValue why? //
$stmt = $con->prepare("INSERT INTO $table(ID, $fields) VALUES (?, ?)");
$stmt->bindValue(1,'',PDO::PARAM_STR);
$stmt->bindValue(2,$values,PDO::PARAM_STR);
$stmt->execute();
//if I remove `bindValue` and replace this it will insert //
$stmt = $con->prepare("INSERT INTO $table(ID, $fields) VALUES ('', $values)");
why after I add bindValue my insert wont work anymore , but when I use normal sql , it will work , what wrong with my bindValue and the VALUES (?,?) ,can anyone help me take a look ??
I am late here, but a Simple handy function that could used anyone searching for the answer to achieve binding and inserting to any table and fields. Haven't included PDO::PARAM_STR as its default ant i see that your fields are all string values. Hope this helps :)
//get array containing fields and its values to be added $fv_array
$fv_array=array(
"field_one_name"=>$field_one_value,
"field_two_name"=>$field_two_value,
"field_three_name"=>$field_three_value
);
$con=new PDO ('mysql:host=localhost;dbname=air','root','123456');
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$fv="";
//create string like :field_one_name,:field_two_name,:field_three_name,
foreach($fv_array as $field=>$value {$fv.=":".$field.",";}
//rtrim removes trailing comma
$statement=$con->prepare("INSERT INTO ".$table." (".implode(",",array_keys($fv_array)).") VALUES (".rtrim($fv, ",").")");
//bind values
foreach($fv_array as $field=>$value){$statement->bindValue(':'.$field,$value);}
$statement->execute();
I am not sure what $fields and $values are but i assume there is nothing wrong with these. You are trying to pass a bindValue of string into an id field. Can you try and change it to PDO::PARAM_INT ?
Related
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;
}
I have some method to insert some data into a database like this:
public function register($username, $email, $hashedPassword, $activationCode)
{
try {
$conn = Database::getConnection();
// Connect and create the PDO object
$conn->exec('SET CHARACTER SET utf8'); // Sets encoding UTF-8
// Define and prepare an INSERT statement
$sql = 'INSERT INTO users (username, email, pass, reset_token, dateAdded )
VALUES (:username, :pass, :email, :token, now())';
$sqlprep = $conn->prepare($sql);
// Adds value with bindParam
$sqlprep->bindParam(':username', $username, PDO::PARAM_STR);
$sqlprep->bindParam(':email', $email, PDO::PARAM_STR);
$sqlprep->bindParam(':pass', $hashedPassword);
$sqlprep->bindParam(':token', $activationCode);
// If the query is successfully executed, output the value of the last insert id
if ($sqlprep->execute()) {
//echo 'Succesfully added the row with id='. $conn->lastInsertId();
$this->result = true;
}
$conn = null; // Disconnect
} catch (PDOException $e) {
include('../views/error.php');
include('../views/admin/includes/footer.php');
exit();
}
}
The problem is I think it's not a good method if I have so many arguments for my function to enter into a database. So is it any good way I can enter a lot of fields just by using 1 parameter but still using bindParam? Since I see a lot of examples is only using prepare without bindParam. I think I can use an array, but I don't know the proper way to do it. So I need some help how I can do it.
since you want keep your bindparam i suggest you use input like this:
$input = array('username' => $username, 'activationHash' => $activationHash);
and in your bindParam add a code like this:
public function register($input){
//code
$sqlprep->bindParam(':username', $input['username'], PDO::PARAM_STR);
//other
}
hope this will solve your problem
https://stackoverflow.com/a/10060755/1747411
Check second example, you have to repeat values with binds
e.g
VALUES (:username1, :pass1, :email1, :token1, now()), (:username2, :pass2, :email2, :token2, now())
and bindParam with loop
You can insert the params as an array into $sqlprep->execute($param_array)
Or, simply passing each param into an array inside execute, like this: $sqlprep->execute(array($param1, $param2))
Update:
Pass values into $input as an array:
$input = array('username' => $username, 'activationHash' => $activationHash); //and so on
Now on the model side,
You can bind these values to params using foreach loop like this:
foreach ($values as $key => $value) {
$sqlprep->bindParam(':' . $key, $value , PDO::PARAM_STR);
}
First of all, I apologize if this is answered somewhere else, but I couldn't find anything.
I have problems with the following code:
function register_user ($register_data) {
global $db;
array_walk ($register_data, 'array_sanitize');
$register_data ['password'] = md5 ($register_data ['password']);
$fields = '`' . implode ('`, `', array_keys ($register_data)) . '`';
$data = '\'' . implode ('\', \'', $register_data) . '\'';
$query = $db -> prepare ("INSERT INTO `users` (:fields) VALUES (:data)");
$query -> bindParam (':fields', $fields);
$query -> bindParam (':data', $data);
$query -> execute ();
}
The problem is that this is executed correctly but the query is not ran and the row is not inserted in the database.
Now, if I just do this:
$query = $db -> prepare ("INSERT INTO `users` ($fields) VALUES ($data)");
//$query -> bindParam (':fields', $fields);
//$query -> bindParam (':data', $data);
$query -> execute ();
everything works like a charm, so I am guessing the problem is with how I am passing data to the placeholders.
Can someone please explain to me why this is not working? I'd like to understand it properly in the first place.
Thanks in advance for any help.
There are two different use cases that could be described as Passing an imploded array to a query placeholder. One is using prepared statements with IN() clause in SQL. this case is already fully covered in this answer.
Another use case is an insert helper function, like one featured in your question. I've got an article that explains how to create an SQL injection proof insert helper function for PDO_MYSQL.
Given such a function is not only adding data values to the query but also table and column names, a prepared statement won't be enough to protect from SQL injection. Hence, such a function will need a helper function of its own, to protect table and field named. Here is one for MySQL:
function escape_mysql_identifier($field){
return "`".str_replace("`", "``", $field)."`";
}
And now we can finally have a function that accepts a table name and an array with data and runs a prepared INSERT query against a database:
function prepared_insert($pdo, $table, $data) {
$keys = array_keys($data);
$keys = array_map('escape_mysql_identifier', $keys);
$fields = implode(",", $keys);
$table = escape_mysql_identifier($table);
$placeholders = str_repeat('?,', count($keys) - 1) . '?';
$sql = "INSERT INTO $table ($fields) VALUES ($placeholders)";
$pdo->prepare($sql)->execute(array_values($data));
}
that can be used like this:
prepared_insert($pdo, 'users', ['name' => $name, 'password' => $hashed_password]);
the full explanation can be found in the article linked above, but in brief, we are creating a list of column names from the input array keys and a list of comma separated placeholders for the SQL VALUES() clause. And finally we are sending the input array values into PDO's execute(). Safe, convenient and concise.
please help , this is not inserting into db
$dbh = new PDO('mysql:host=localhost;dbname=blog', root, root);
if($dbh){
// use the connection here
$stmt = $dbh->prepare("INSERT INTO comments (blog_id,dateposted,name,comment) VALUES (:blog_id,:dateposted,:name,:comment)");
$stmt->bindParam(':blog_id', $validentry);
$stmt->bindParam(':dateposted', NOW());
$stmt->bindParam(':name', $_POST['name']);
$stmt->bindParam(':comment', $_POST['comment']);
$stmt->execute();
// and now we're done; close it
}else{
echo mysql_error();
}
$dbh = null;
//redirect after posting
$stmt->bindParam(':dateposted', NOW());
PDOStatement::bindParam() binds the parameter to a PHP variable reference. As such, it requires the second argument to be a variable.
You can instead use PDOStatement::bindValue() to use a literal or return value from a function.
Also, NOW() is not a PHP function and as such, cannot be used here. If you're just wanting to use the DB function, hard-code it into the statement, eg
INSERT INTO comments (blog_id,dateposted,name,comment)
VALUES (:blog_id, NOW(), :name, :comment)
change NOW() to date('Y-m-d H:i:s')
Phil, ok, but if you need the bindParam to assign a value depending a condition?
In my case, I want to let the user define the creation date if he wants to.
$stmt = $conn->prepare('INSERT INTO news (title_fr, content_fr, creation_date) VALUES (:title_fr, :content_fr, :creation_date)');
if( $date ) {
$stmt->bindParam(':creation_date', $date);
} else {
$stmt->bindParam(':creation_date', NOW());
}
Thanks for looking. All helpful answers/comments are up voted.
In php, you can use NOW() like this:
mysql_query("INSERT INTO tablename (id, value, time_created)
VALUES ('{$id}', '{$value}', NOW())");
How can I do the same thing in PDO. When I bind like this, I get an error:
$stmt->bindParam(':time_added', NOW(), PDO::PARAM_STR);
Is it the PDO:PARAM_STR?
Because nobody has explicitly answered the question, I'll add the correct answer for the sake of completeness.
$stmt = $pdoDb->prepare('INSERT INTO tablename (id, value, time_created) VALUES (:id, :value, NOW())');
// either bind each parameter explicitly
$stmt->bindParam(':id', $id); // PDOStatement::bindValue() is also possibly
$stmt->bindParam(':value', $value);
$stmt->execute();
// or bind when executing the statement
$stmt->execute(array(
':id' => $id,
':value' => $value
));
Presuming your PDO statement is correct you could do something like this:
$date = date('Y-m-d H:i:s');
$stmt->bindParam(':time_added', $date, PDO::PARAM_STR);
None of the answers solve the question as I see it!
So there are some of my findings:
there is NO WAY how to force PDO to pass MySQL function call as a query value - so there is no way to do simple wrapper that will be able to use NOW() or any other function as passed values. Every time you need something like that, you need manually change the query, so the function call is part of the query string. :-(
I'm using function that tests given values for MySQL function I am using and modifies the query itself, but it is not a good solution to my opinion... :-}
This might be useful to some of you, maybe not. I was confronted with the same problem as Ollie Saunders was. I'm pretty new to php/mysql, and most of all PDO. I was able to solve the problem with the following:
$active = 0;
$id = NULL;
$query = "INSERT
INTO tbl_user(ID_user, firstname, lastname, email, password, active, create_date)
VALUES (?,?,?,?,?,?,NOW())";
if($stmt=$this->conn->prepare($query)) {
$stmt->bind_param('issssi', $id, $firstname, $lastname, $email, $password, $active);
$stmt->execute();
}
and guess what it works! Hope to have helped here. Any comments are welcome. Try it and tell me if it worked for you, or if you have any additions.
To answer Elmo's question, you can create a PDO wrapper that allows for SQL functions like NOW(). You just need to pass an additional argument with the columns that you want to use SQL functions for. Here's mine:
function pInsertFunc($action, $table, $values, $sqlfunctions)
{
global $pdb;
// There's no way to pass an SQL function like "NOW()" as a PDO parameter,
// so this function builds the query string with those functions. $values
// and $sqlfunctions should be key => value arrays, with column names
// as keys. The $values values will be passed in as parameters, and the
// $sqlfunction values will be made part of the query string.
$value_columns = array_keys($values);
$sqlfunc_columns = array_keys($sqlfunctions);
$columns = array_merge($value_columns, $sqlfunc_columns);
// Only $values become ':paramname' PDO parameters.
$value_parameters = array_map(function($col) {return (':' . $col);}, $value_columns);
// SQL functions go straight in as strings.
$sqlfunc_parameters = array_values($sqlfunctions);
$parameters = array_merge($value_parameters, $sqlfunc_parameters);
$column_list = join(', ', $columns);
$parameter_list = join(', ', $parameters);
$query = "$action $table ($column_list) VALUES ($parameter_list)";
$stmt = $pdb->prepare($query);
$stmt->execute($values);
}
Use it like this:
$values = array(
'ID' => NULL,
'name' => $username,
'address' => $address,
);
$sqlfuncs = array(
'date' => 'NOW()',
);
pInsertFunc("INSERT INTO", "addresses", $values, $sqlfuncs);
The query string that results looks like this:
INSERT INTO addresses (ID, name, address, date) VALUES (:ID, :name, :address, NOW())
other than NOW() i also utilize the "timestamp" type column and set its default to CURRENT_TIMESTAMP .. so i just pass nothing for that field and time is automatically set. maybe not exactly what ur looking for.