i have a data array e.g. this:
$data = ['ver_weather' => $post["weathercondition"],
'ver_flash' => $post["flashintense"],
'ver_earth' => $post["earthrumble"]]
these data i use in my sql like this:
$sql = "INSERT INTO `database`.`table` (`weather`, `flash`, `earth`)
VALUES (:ver_weather, :ver_flash, :ver_eart)";
$pdo->prepare($sql)->execute($data);
The result is something like:
INSERT INTO `database`.`table` (`weather`, 'flash', `earth')
VALUES ('1'weather, '1'flash, '1'earth)
So is pdo replacing parts of my keys with the value ?
what is wrong there ?
thanks for helping me out.
edit: Execute does work with named bindings so you could just edit your $data array like this:
$data = [':ver_weather' => $post["weathercondition"],
':ver_flash' => $post["flashintense"],
':ver_earth' => $post["earthrumble"]]
Note the : at the beginning of each key
Original answer below...
I think the issue is that you're trying to bind by name and I don't think PDOStatement supports named bindings. I'd recommend trying the following:
$data = [$post["weathercondition"], $post["flashintense"], $post["earthrumble"]];
$sql = "INSERT INTO `database`.`table` (`weather`, `flash`, `earth`)
VALUES (?, ?, ?)";
$pdo->prepare($sql)->execute($data);
Related
At this specific moment, I want to know how to insert two records into DB. Both are almost the same, except only one single column value changes.
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$columns = array('col1','col2', 'col3', 'col4', 'col5');
$values = array(
$db->quote(A),
$db->quote(x1),
$db->quote(x2),
$db->quote(x3),
$db->quote(x4)
);
$values = array(
$db->quote(B),
$db->quote(x1),
$db->quote(x2),
$db->quote(x3),
$db->quote(x4)
);
...
As you can see, only first value changes. Is there some elegant way to do this?
You code seems to be incomplete since it does not assign your values to the query.
Try this instead. It shows how to add the content of $foo to the column myColumn in the table #__mytable.
$query->insert($db->quoteName('#__mytable'))
->columns('myColumn');
->values(implode(',', array(
$db->quote($foo)
)));
$query->execute();
For multiple values this would help:
foreach($myValues as $myValue) {
$query->values(implode(',', array(
$db->quote($myValue),
)));
}
While there is just one value in my example, it is ready to add multiple columns if needed. Just extend the columns() and values() methods.
I am using Yii2 advance template. I have to insert 1000 to 2000 records in MySql Database.
Is it possible to make Multiple UPSERT Query in Yii2.
Please help me with your suggestion/answers. Thank you.
Since version 2.0.14 you have upsert() available.
Your code could look something like this:
$insertValues = [
'timestamp' => gmdate('YmdH'),
'entry_id' => $this->id,
'view_count' => 1,
];
$updateValues = ['view_count' => new \yii\db\Expression('table_name.view_count + 1')];
Yii::$app->db->createCommand()->upsert('table_name', $insertValues, $updateValues)->execute();
You can find the full documentation here: https://www.yiiframework.com/doc/api/2.0/yii-db-command#upsert()-detail
Try with modified batchInsert() method:
$db = \Yii::$app->db;
$sql = $db->queryBuilder->batchInsert($table, $fields, $rows);
$db->createCommand($sql . ' ON DUPLICATE KEY UPDATE')->execute();
I'm using the following code. The code works, but I want to change it so that it uses bindparam
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
$stqid=array();
for ($i=0; $i<$array_count; $i++){
$stqid[$i][0]=$lastInsertValue;
$stqid[$i][1]=$qid[$i][0];
$stqid[$i][2]=$qid[$i][1];
}
$values = array();
foreach ($stqid as $rowValues) {
foreach ($rowValues as $key => $rowValue) {
$rowValues[$key] = $rowValues[$key];
}
$values[] = "(" . implode(', ', $rowValues) . ")";
}
$count = $dbh->exec("INSERT INTO qresults(instance, qid, result) VALUES ".implode (', ', $values));
$dbh = null;
}
catch(PDOException $e){
echo $e->getMessage();
}
I replaced the following
$count = $dbh->exec("INSERT INTO qresults(instance, qid, result) VALUES ".implode (', ', $values));
with
$sql = "INSERT INTO qresults (instance, qid, result) VALUES (:an_array)";
$stmt = $dbh->prepare($sql);
$stmt->bindParam(':an_array', implode(',', $values),PDO::PARAM_STR);
$stmt->execute();
but the insert doesn't work anymore (I didn't get any error messages though).
QUESTION: What am I doing wrong? How can I rewrite the code to use bindParam?
You're trying to create a statement and bind a param.
Statement are great because it potentially nullify any kind of SQL injection. And it does it by removing the concept of a query being only seen as a string. The SQL query is seen as a string with a parameter list and an the associated data as binded variables.
So the query is not only text, but text + data.
I mean:
This simple query:
SELECT * FROM A WHERE val="$param"
It is not safe because the query is only viewed as a string. And if $param is not checked, it is a SQLi hole.
But when create a statement, your query becomes:
SELECT * FROM A WHERE val=:param
Then you use bindparam to specify the value a :param. Which mean the value is not appended to the query string, but the query is already parsed and the data is provided.
In your case, you bind to the param :array an imploded array (I assume "data1", "data2", etc..). Which is only one parameter with the value as a string ( "data1, data2, data3..." ), so it will only result in one insert and not multiple insertions.
You can change your statement generation by generating a query with enough parameters to handle your array
$sql = "INSERT INTO qresults (instance, qid, result) VALUES ( :val0, :val1, :val2, ...)";
Then loop on your array and call the bindparam method for each parameters.
$count = 0;
foreach($values as $val)
{
$stmt->bindParam(":val$count", $val,PDO::PARAM_STR);
$count++;
}
This will work.
Edit: This solution show how it works for a one dimensional array, but can be easily extended to your problem by tweaking the statement query generation and modify the bindparam loop.
Your statement should looks like:
$sql = "INSERT INTO qresults (instance, qid, result) VALUES (:val0, :val1, :val2) , (:val3, :val4, :val5), ...";
You just have to count the number of element in your base array.
This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 18 days ago.
I'm using the following php pdo code to insert data into mysql database, the insertion succeeded, however, the updated database is showing the string literals ':a', ':b' as values in respectively field. what's wrong?
$data = array(
array('a' => 'John', 'b' => 'OK'),
);
$st=$dbh->prepare("insert into mytable (a, b) values(':a', ':b')");
$st->execute($data) or print_r($st->errorInfo());
Remove the quotes from your placeholders. Otherwise, they are treated as string literals and directly inserted.
$st=$dbh->prepare("insert into mytable (a, b) values(:a, :b)");
And remove the nesting on your array:
// $data is an associative array, it should not contain another array!
$data = array('a' => 'John', 'b' => 'OK');
To be consistent, I prefer to use the : on the placeholder array keys:
$data = array(':a' => 'John', ':b' => 'OK');
You need to define your array the same in the sql and the parameters, you're missing the ":". You also don't need two arrays, only one.
$data = array(':a' => 'John', ':b' => 'OK');
The query also does not need quotes, since PDO already knows it's a parameter
$st=$dbh->prepare("insert into mytable (a, b) values(:a, :b)");
$st->execute($data) or print_r($st->errorInfo());
You are executing a prepared statement with named placeholders. So, you need to remove quotes from your placeholders, otherwise they are treated as a values for respective columns and directly updated.
To be consistent, I prefer to use the : on the placeholder array keys:
$data = array(':a' => 'John', ':b' => 'OK');
$st=$dbh->prepare("insert into mytable (a, b) values(:a, :b)");
You can also execute a prepared statement with question mark placeholders:
$data = array(
array('John','OK'),
);
$st=$dbh->prepare("insert into mytable (a, b) values(?, ?)");
$st->execute($data) or print_r($st->errorInfo());
My technical blog didn't get off to a good start as Wordpress wouldn't save my post that contained PHP, HTML and SQL code. I'll have to modify Wordpress sanitation methods or roll my own basic blogging platform but what is the correct and safe way to store technical text with this kind of content in a MySQL database?
I assume you're using php.
Best is to use PDO, see: http://www.php.net/manual/en/pdo.prepare.php
From that site
Example #1 Prepare an SQL statement with named parameters
<?php
/* Execute a prepared statement by passing an array of values */
$sql = 'SELECT name, colour, calories
FROM fruit
WHERE calories < :calories AND colour = :colour';
$sth = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute(array(':calories' => 150, ':colour' => 'red'));
$red = $sth->fetchAll();
$sth->execute(array(':calories' => 175, ':colour' => 'yellow'));
$yellow = $sth->fetchAll();
?>
Example #2 Prepare an SQL statement with question mark parameters
<?php
/* Execute a prepared statement by passing an array of values */
$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < ? AND colour = ?');
$sth->execute(array(150, 'red'));
$red = $sth->fetchAll();
$sth->execute(array(175, 'yellow'));
$yellow = $sth->fetchAll();
?>
Alternatively use escaping
Use mysql_real_escape_string() to escape values before inserting them into the query.
$val1 = mysql_real_escape_string($_POST['value1']);
$query = "SELECT a,b,c FROM table1 WHERE a = '$val1' ";
// the quotes are essential ^ ^
Outputting code as code
When outputting the content use:
echo "the output is: ".htmlentities($output);