pdo array getting Array to string conversion error - php

When I run this code it should store ben in the database but, it says Array in the first_name column and it gives the string to conversion error. How would I get rid of the error?
<?php $data = ['first_name' => 'ben'] ?>
<?php $sql = "INSERT INTO names (first_name) values (?);" ?>
<?php $statement = $pdo->prepare($sql); ?>
<?php $statement->execute([$data]); ?>

PDO has two different ways to bind parameters. The first is positional. In this case, the array you pass to execute() should be an indexed array, with values in the same order that you want them to bind to the question marks:
$sql = "INSERT INTO table (col1, col2) values (?, ?)";
$data = ['value for col1', 'value for col2'];
Note the values must be in the same order that they're going to be used:
$data = ['value for col2', 'value for col1']; // This won't work, wrong order!
The alternative (and in my opinion, superior) method is to use named parameters. Here, you need to use an associative array with a key named the same as your parameter placeholder.
$sql = "INSERT INTO table (col1, col2) values (:col1, :col2)";
$data = ['col1' => 'value for col1', 'col2' => 'value for col2'];
The order of these now does not matter because they're keyed by the array name instead of the position:
$data = ['col2' => 'value for col2', 'col1' => 'value for col1']; // Still good!
Your problem (in addition to the extra array wrap that #Sammitch pointed out) is that you have mixed these two techniques together in an incompatible way -- you're using positional parameters, but have provided an associative array. So, in your case, you either need to use positional parameters and an indexed array:
$data = ['ben'];
$sql = "INSERT INTO names (first_name) values (?);";
$statement = $pdo->prepare($sql);
$statement->execute($data);
Or named parameters and an associative array:
$data = ['first_name' => 'ben'];
$sql = "INSERT INTO names (first_name) values (:first_name);";
$statement = $pdo->prepare($sql);
$statement->execute($data);

Related

How storing array values in different columns of table using php

Here is the piece of code so far I've tried:
$month = array('red','green','red');
$values = array();
foreach($month as $dataset)
{
$values[] = ($dataset);
}
$columns = implode(", ",array_keys($values));
$escaped_values = array_values($values);
$valu = implode(", ", $escaped_values);
$sql = "INSERT INTO abc (col1,col2,col3) VALUES ('$valu');";
Here is the output:
Error: INSERT INTO abc (col1,col2,col3) VALUES ('red, green, red');
Column count doesn't match value count at row 1
What I am trying to do is to store values in the array where the value of the array may vary depending upon the value the user gave, and then store it in different columns. For example, if the total columns are 3 and array value is 2 then store values in col1 and col2 and null value in col3.
With the single quotes around the whole string 'red, green, red' that is the value for col1 only.
It should look more like this 'red','green','red'.
So quick fix is this $valu = implode("','", $escaped_values);
Added a single quotes inside your implode.
The outside quotes will be captured in the final statement as detailied in the problem above:
$sql = "INSERT INTO abc (col1,col2,col3) VALUES ('$valu');";
Here the Code after making it work properly
$month = array('red','green','red');
$values = array();
foreach($month as $dataset)
{
$values[] = "'{$dataset}'";
}
$columns = implode(", ",array_keys($values));
$escaped_values = array_values($values);
$valu = implode(", ", $escaped_values);
$sql = "INSERT INTO abc (col1,col2,col3) VALUES ($valu);";
The values are into the single quote. Please check below example.
INSERT INTO abc (col1,col2,col3) VALUES ('red', 'green', 'red');
No one else seems to have addressed the actual issue.
What I am trying to do is to store values in the array where the value
of the array may vary depending upon the value the user gave, and then
store it in different columns. For example, if the total columns are 3
and array value is 2 then store values in col1 and col2 and null value
in col3.
So if the values come in as an array at different lengths, and you want to insert as null or limit to the max length of the columns then you can do it like the following.
Ideally, you want to produce an array which looks like:
$data = [
'col1' => 'red',
'col2' => 'green',
'col3' => null
];
To do that without any looping define the database columns, then create an array of the same length of null values, then slice the input array to the same length and merge, this will produce an array like above.
<?php
$columns = [
'col1',
'col2',
'col3',
];
$month = [
'red',
'green'
];
$data = array_combine(
$columns,
array_slice($month, 0, count($columns))+array_fill(0, count($columns), null)
);
Now you simply need to implode the array into your query, using ? for placeholders for the prepared query.
$sql = '
INSERT INTO abc (
'.implode(', ', array_keys($data)).'
) VALUES (
'.implode(', ', array_fill(0, count($data), '?')).'
)';
Will produce:
INSERT INTO abc (
col1, col2, col3
) VALUES (
?, ?, ?
)
Then just do your query, for example:
$stmt = $pdo->prepare($sql);
$stmt->execute($data);
Simple clean and safe.

Binding array in PDO

We have some array of values that want to insert them to the database.
for example:
$first_Names = array("Bob","John","Paolo","Jack", "Alex");
$last_Names = array("Charlton", "Smith", "Maldini", "Rooney", "anotherlastname");
Now I want to insert them to database
$sql = "INSERT INTO people(fname, lname) VALUES(:fname, :lname)";
Can I bind array directly without using foreach command and insert them one by one items?

How to bind multiple params to prepare statement [duplicate]

Is there's an easy way of binding multiple values in PDO without repitition ? Take a look at the following code :
$result_set = $pdo->prepare("INSERT INTO `users` (`username`, `password`, `first_name`, `last_name`) VALUES (:username, :password, :first_name, :last_name)");
$result_set->bindValue(':username', '~user');
$result_set->bindValue(':password', '~pass');
$result_set->bindValue(':first_name', '~John');
$result_set->bindValue(':last_name', '~Doe');
$result_set->execute();
Here, I binded values in a repepeated way which is 4 times. So is there's an easy way of binding multiple values in PDO ?
You can always bind values within the arguments of execute() as long as you're fine with the values being treated as PDO::PARAM_STR (string).
$result_set = $pdo->prepare("INSERT INTO `users` (`username`, `password`, `first_name`, `last_name`) VALUES (:username, :password, :first_name, :last_name)");
$result_set->execute(array(
':username' => '~user',
':password' => '~pass',
':first_name' => '~John',
':last_name' => '~Doe'
));
You can use the array passed just like any array:
$user = "Nile";
$pdo->execute(array(":user" => $user));
If you want to bind based on type (string, int, etc), then no. If you're fine with binding everything as a string:
$stmt = $db->prepare("...");
$stmt->execute(array(
'foo' => 'bar',
'something' => 'else',
'third' => 'thing',
));
To truly never type anything twice, you can use an array to supply the data, and use a function on that same array to output the binding portion of the MySQL query. For example:
function bindFields($fields){
end($fields); $lastField = key($fields);
$bindString = ' ';
foreach($fields as $field => $data){
$bindString .= $field . '=:' . $field;
$bindString .= ($field === $lastField ? ' ' : ',');
}
return $bindString;
}
The data and column names come from a single associative array ($data). Then, use bindFields($data) to generate a string of column = :column pairs to concatenate into the MySQL query:
$data = array(
'a_column_name' => 'column data string',
'another_column_name' => 'another column data string'
);
$query = "INSERT INTO tablename SET" . bindFields($data);
$result = $PDO->prepare($query);
$result->execute($data);
bindFields($data) output:
a_column_name=:a_column_name,another_column_name=:another_column_name

Error in yii insert statement SQLSTATE[HY093]: Invalid parameter number: parameter was not defined

While inserting data into a table in Yii, I am getting this error:
CDbCommand failed to execute the SQL statement:
SQLSTATE[HY093]: Invalid parameter number: parameter was not defined.
The SQL statement executed was: insert into user_feedback (name,
desc,email,mobilenumber) values (:Name, :Desc,:email,:Mobilenmber).
below is my code :
$sql = "insert into user_feedback (name, desc,email,mobilenumber) values (:Name, :Desc,:email,:Mobilenmber)";
$parameters = array(":name"=>$_POST['Name'], ':desc' => $_POST['Desc'],':email'=>$_POST['email'],':mobile_number'=>$_POST['Mobile_nmber']);
Yii::app()->db->createCommand($sql)->execute($parameters);
You have 2 mistakes on your request. As Alexander said, your parameters didn't match (all expect email). And there is typo mistake.
This request/param should work :
$sql = "insert into user_feedback (name, desc,email,mobilenumber) values (:name, :desc,:email,:mobile_number)";
$parameters = array(":name"=>$_POST['Name'], ':desc' => $_POST['Desc'],':email'=>$_POST['email'],':mobile_number'=>$_POST['Mobile_number']);
Fix the parameter name to match the ones in select statement, try executing this using queryAll as follows :
$sql = "insert into user_feedback (name, desc,email,mobilenumber) values (:Name, :Desc,:Email,:Mobilenmber)";
$parameters = array(
":Name"=>$_POST['Name'], // names match paremeters in select
':Desc' => $_POST['Desc'], // names match paremeters in select
':Email'=>$_POST['email'], // names match paremeters in select
':Mobilenmber'=>$_POST['Mobile_number']); // names match paremeters
// in select plus there is a problem
// with with key (typo) Mobile_number and not Mobile_nmber (unless you defined it this way on purpose !!!)
$command = Yii::app()->db->createCommand($sql);
$result = $command->queryAll(true,$parameters);
Edit
I bet the issue is really with the name column, it is a MYSQL keyword name, please change the column name to something else and try it out

How do i implement 'INSERT' using PHP PDO

Using PHP's PDO and prepared statements, how do I implement the following?
$sql = 'insert into $tablename ($var1, $var2, $var3, ...) VALUES (:placeholder1, :placeholder2, ...)';
Thanks.
Here is one way to do it:
$sth = $dbh->prepare('INSERT INTO '.$tablename.' ('.implode(',', array_keys($inserting)).') VALUES ('.str_pad('', count($inserting)*2-1, '?,').')');
$sth->execute(array_values($inserting));
Where $tablename is the name of the table and $inserting is an associative array with keys being the names of the columns and the values of the array being the values to insert.

Categories