I am trying to insert multiple lines in a single query based on this example:
[a link][1]: http://thisinterestsme.com/pdo-prepared-multi-inserts/
But the values are not inserted.
$pdo = new PDO("mysql:host=$this->host;dbname=$this->database", $this->login,
$this->password);
$columnNames = array_keys($dataVals[0]);
unset($columnNames["8"]);
unset($columnNames["9"]);
foreach ($dataVals as $arrayIndex => $row) {
$params = array();
foreach ($row as $columnName => $columnValue) {
$param = ":".$columnName.$arrayIndex;
$params[] = $param;
$toBind[$param] = $columnValue;
}
$rowsSQL[] = "(".implode(", ", $params).")";
}
$sql = "INSERT INTO `$this->table` (".implode(", ", $columnNames).") VALUES ".implode(", ", $rowsSQL);
$pdoStatement = $pdo->prepare($sql);
foreach ($toBind as $param => $val) {
$pdoStatement->bindParam($param, $val);
}
$pdoStatement->execute();
Related
the problem is my function insert inserts my record in two rows.
this is my code to connect to database in a file named :
connect.php
<?php
try{
$db = new PDO("mysql:host=localhost;dbname=NPD" , "root" , "");
echo "connected";
}
catch(Exception $e){
echo $e->getMessage();
}
this is my database class in a file
database.php
<?php
require 'connect.php';
class DB {
public function insertInto($tableName , $info){
global $db;
foreach ($info as $coloumnName => $coloumnValue) {
$stmt = $db->prepare("INSERT INTO $tableName ($coloumnName) VALUES ('$coloumnValue') ");
$stmt->execute();
}
}
}
$da = new DB;
$da->insertInto('tableOne',array('name' => 'lolo' , 'deg' => '100'));
the result in the database is :
tableOne
how can to make the insert function inserts my record in one row.
note : i want to insert any number of columns and values.
try to do something like this:
$arr = array('name' => 'lolo' , 'deg' => '100');
$columns=array_keys($arr);
$values=array_values($arr);
$str="INSERT INTO $tableName (".implode(',',$columns).") VALUES ('" . implode("', '", $values) . "' )";
echo $str;//your sql
// $stmt = $db->prepare($str);
// $stmt->execute();//uncomment to execute
Like this but there are some concerns ( also I haven't tested this )
class DB {
protected $_conn;
public function __construct( $user, $pass, $database='NPD', $host='localhost' ){
try{
$this->_conn = new PDO("mysql:host={$host};dbname={$database}" , $user , $pass);
echo "connected";
}catch(Exception $e){
echo $e->getMessage();
}
}
public function insertInto($tableName , $info){
$sql = 'INSERT INTO $tableName (';
$sql .= '`'implode('`,`', array_keys($info[0])).'`';
$sql .= ')VALUES';
foreach ($info as $index => $row) {
$sql .= '(';
foreach( $row as $column => $value){
$sql .= ':'.$column.$index.',';
$params[':'.$column.$index] = $value;
}
$sql = rtrim($sql, ',');
$sql .= '),';
}
$sql = rtrim($sql, ',');
$stmt = $this->_conn->prepare($sql);
$stmt->execute($params);
}
}
}
$da = new DB('root', '');
$da->insertInto('tableOne',array( array('name' => 'lolo' , 'deg' => '100') ) );
First of all you loose any sql injection protection on the column names. If you can manage the placeholders on the values, then that is ok, but without using them there you loose protection on that as well. This can be solved by using the db schema itself, via Show columns but that gets a wee bit complex.
https://dev.mysql.com/doc/refman/5.7/en/show-columns.html
Second, your input array structure is all wrong, it needs to be array(0=>array(...), 1=>array(...)) instead of just array(...)
Third I would make this class a "Singleton" but that's just me
http://coderoncode.com/design-patterns/programming/php/development/2014/01/27/design-patterns-php-singletons.html
Forth, if you just want to do a single row at a time you can change this method
public function insertInto($tableName , $info){
$sql = 'INSERT INTO $tableName (';
$sql .= '`'implode('`,`', array_keys($info)).'`';
$sql .= ')VALUES(';
$params = array();
foreach( $info as $column => $value){
$sql .= ':'.$column.$index.',';
$params[':'.$column.$index] = $value;
}
$sql = rtrim($sql, ',');
$sql .= ')';
$stmt = $this->_conn->prepare($sql);
$stmt->execute($params);
}
And use the current input array structure you have.
This Is how i coded my own insert function
public function insertRecord($table,$records){
//A variable to store all the placeholders for my PDO INSERT values.
$placeholder = '';
for ($i = 0; $i < sizeof($records); $i++){
$placeholder[$i] = '?';
}
//A FOR-LOOP to loop through the records in the $record array
$placeholder = implode(',', $placeholder);
//Imploding ',' in between the placeholders
$sql = "INSERT INTO ".$table." VALUES ("{$placeholder}")";
$query = $this->dbh->prepare($sql);
$query->execute($records);
}
It Might not be the best..worked for me though.
As some other answers/comments have stated, there are quite a few critiques one could make about this overall process. However, in the interests of simply answering the question, you may want to just build the statement by looping through the columns, then looping through the values, then executing the finished statement (code below is just an example and hasn't been tested):
require 'connect.php';
class DB {
public function insertInto($tableName , $info){
global $db;
$query = "INSERT INTO $tableName (";
$columns = array_keys($info);
// build the columns in the statement
$length = count($columns);
foreach($columns as $index => $column) {
$query .= "$column";
if ($index+1 < $length) {
$query .= ','
}
}
$query .= ") VALUES ("
// build the values in the statement
$i = 1;
$length = count($info);
foreach($info as $value) {
$query .= "'$value'"
if ($i < $length) {
$query .= ","
}
$i++;
}
$query .= ")"
$stmt = $db->prepare($query);
$stmt->execute();
}
}
$da = new DB;
$da->insertInto('tableOne',array('name' => 'lolo' , 'deg' => '100'));
Hi I have some problems with merging my array and bind my params.
Error Message = Warning: mysqli_stmt::bind_param(): Number of elements
in type definition string doesn't match number of bind variables
in.......
$headline = $_GET['hl'];
$county = $_GET['ca'];
$categories = $_GET['co'];
$query = 'SELECT COUNT(id) FROM main_table';
$queryCond = array();
$stringtype = array();
$variable = array();
if (!empty($headline)) {
$queryCond[] = "headline LIKE CONCAT ('%', ? , '%')";
array_push($stringtype, 's');
array_push($variable, $headline);
}
if (!empty($county)) {
$queryCond[] = "county_id = ?";
array_push($stringtype, 'i');
array_push($variable, $county);
}
if (!empty($categories)) {
$queryCond[] = "categories_id = ?";
array_push($stringtype, 'i');
array_push($variable, $categories);
}
if (count($queryCond)) {
$query .= ' WHERE ' . implode(' AND ', $queryCond);
}
//var_dump($query);
$stmt = $mysqli->prepare($query);
$variable = array_merge($stringtype, $variable);
print_r($variable);
//var_dump($refs);
$refs = array();
foreach($variable as $key => $value)
$refs[$key] = &$variable[$key];
call_user_func_array(array($stmt, 'bind_param'), $refs);
You need change this:
$variable = array_merge($stringtype, $variable);
$refs = array();
foreach($variable as $key => $value)
$refs[$key] = &$variable[$key];
to this:
$variable = array_combine($stringtype, $variable);
Because array_combine() create an array by using one array for keys and another for its values.
Read more at:
http://php.net/manual/en/function.array-combine.php
It's a bit late answer, but I had issue with dynamically adding values.
If you have php v +5.6, you can omit this part
$variable = array_merge($stringtype, $variable);
// and $refs
call_user_func_array(array($stmt, 'bind_param'), $refs);
and using ...token introduced in +5.6v.
Here is a fully work example for my case:
// establish mysqli connection
$conn = new mysqli(.....);
$tableName = 'users';
// Types to bind
$type = 'isss';
$fields = ['id','name', 'email', 'created'];
$values = [1, 'name', 'email#test.com', '2018-1-12'];
$sql = "INSERT INTO " . $tableName . " (" . join(',', $fields) . ") VALUES (?,?,?,?)";
$stmt = $conn->prepare($sql);
// Using ...token introduced in php v.5.6 instead of call_user_func_array
// This way references can be omitted, like for each value in array
$stmt->bind_param($type, ...$values);
$stmt->execute();
$stmt->close();
Here, I'm inserting the dynamic array values into database table. it inserting the datas into database table perfectly. But, I need a little bit modification with this code.. it inserting the datas with ,. But, I want to store the array values in a separate row.
NOW I GOT
id field_name
1 aaa, bbb, ccc, ddd
BUT I NEED
id field_name
1 aaa
2 bbb
3 ccc
4 ddd
How can I achieve that?
$choose_general_rules = $_POST['choose_general_rules'];
$choose_no_of_questions = $_POST['choose_no_of_questions'];
$choose_mark_questions = $_POST['choose_mark_questions'];
$choose_question_name = $_POST['choose_question_name'];
$question = array();
foreach($choose_question_name as $value) {
$question[] = $value;
}
$result_question = implode(',', $question);
$answer_1 = $_POST['answer_1'];
$answer_one = array();
foreach($answer_1 as $value) {
$answer_one[] = $value;
}
$result_answer_one = implode(',', $answer_one);
$answer_2 = $_POST['answer_2'];
$answer_two = array();
foreach($answer_2 as $value) {
$answer_two[] = $value;
}
$result_answer_two = implode(',', $answer_two);
$answer_3 = $_POST['answer_3'];
$answer_three = array();
foreach($answer_3 as $value) {
$answer_three[] = $value;
}
$result_answer_three = implode(',', $answer_three);
$answer_4 = $_POST['answer_4'];
$answer_three = array();
foreach($answer_3 as $value) {
$answer_three[] = $value;
}
$result_answer_three = implode(',', $answer_three);
try
{
$stmt = $dbh->prepare("INSERT INTO choose_the_correct_answer ( reference_id, general_rules, no_of_questions, mark_each_questions, question, answer_option_one, answer_option_two, answer_option_three, answer_option_four ) VALUES ( :ref_id, :choose_general_rules, :choose_no_of_questions, :choose_mark_questions, :choose_question_name, :answer_1, :answer_2, :answer_3, :answer_4 )");
$stmt->bindParam(':ref_id', $lastid, PDO::PARAM_INT);
$stmt->bindParam(':choose_general_rules', $choose_general_rules, PDO::PARAM_STR);
$stmt->bindParam(':choose_no_of_questions', $choose_no_of_questions, PDO::PARAM_STR);
$stmt->bindParam(':choose_mark_questions', $choose_mark_questions, PDO::PARAM_STR);
$stmt->bindParam(':choose_question_name', $result_question, PDO::PARAM_STR);
$stmt->bindParam(':answer_1', $result_answer_one, PDO::PARAM_STR);
$stmt->bindParam(':answer_2', $result_answer_two, PDO::PARAM_STR);
$stmt->bindParam(':answer_3', $result_answer_three, PDO::PARAM_STR);
$stmt->bindParam(':answer_4', $result_answer_three, PDO::PARAM_STR);
$stmt->execute();
}
catch(PDOException $e)
{
echo "Error Inserting datas into database :" .$e->getMessage();
}
You should change everything in this code:
implode(',', $question);
into
implode("\n", $question);
Of course the same
implode(',', $answer_one);
into
implode("\n", $answer_one);
and so on
I have an array that is built based on dynamic rows that changes every time. I am able to post the array but i get each field in a separate row. How can i insert the array into a single row.
Here is my PHP:
<?php
include_once 'dbconnect.php';
if (isset($_POST['item_name'])) {
$table = $_POST['ItemTypeSelect'];
$array = array();
foreach ($_POST as $key => $variable) {
$chesckColumn = mysql_query("SELECT `$key` from $table");
if (!$chesckColumn) {
echo "column ".$key." does not exist <br/>";
}else{
$results = $variable;
$columnName = $key;
$array[$columnName] = $results;
mysql_query("INSERT INTO $table (`$columnName`) VALUES ('$results') ")or die(mysql_error());
}
}
print_r($array);
}
?>
The print array is :
Array
(
[Server_id] =>
[Server_IP_Address] => 123456789
[Server_IP2] => 123456789
[Server_Name] => Server
)
Any help is appreciated.
$table = $_POST['ItemTypeSelect'];
$isert_vals = "VALUES(";
$insert_table = "INSERT INTO `".$table."` (";
foreach ($_POST as $key => $variable) {
$chesckColumn = mysql_query("SELECT `$key` from $table");
if (!$chesckColumn) {
echo "column ".$key." does not exist <br/>";
} else {
$results = $variable;
$columnName = $key;
$array[$columnName] = $results;
$insert_table.="`".$columnName."`,";
$isert_vals.="'".$results."',";
}
}
$isert_vals = substr($isert_vals , 0 ,-1).") ";
$insert_table = substr($insert_table , 0 ,-1).") ";
$query = $insert_table.$isert_vals;
mysql_query($query);
You need to build one INSERT statement, rather than executing a new one each time you go through your loop.
Also, please note that the mysql_* functions are deprecated - you should use PDO or MySQLi instead.
Finally, you are wide open to SQL injection attacks. Use prepared statements, or all sorts of Very Bad Things will happen to your database, app, server, toaster, and dog.
Something like this should do the trick:
if (isset($_POST['item_name'])) {
$table = mysql_real_escape_string($_POST['ItemTypeSelect']);
$array = array();
$cols = array();
$vals = array();
foreach ($_POST as $key => $variable) {
$key = mysql_real_escape_string($key);
$variable = mysql_real_escape_string($variable);
$chesckColumn = mysql_query("SELECT `$key` from $table");
if (!$chesckColumn) {
echo "column ".$key." does not exist <br/>";
} else {
$cols[] = $key;
$vals[] = $variable;
}
}
$columns = implode(",", $cols);
$values = implode("," , $vals);
mysql_query("INSERT INTO $table ($columns) VALUES ($values)") or die(mysql_error());
}
Be aware that mysql extension is deprecated. Consider using mysqli or PDO.
And note that you should always sanitize your database input to prevent sql-injections.
I found this http://net.tutsplus.com/tutorials/php/the-problem-with-phps-prepared-statements/
and it works really good to have it in a seperate php file which my other files calls to with a query as argument.
Is it possible to make something similar with other queries like insert and update?
This is the updated example:
$params is an array.
function insertToDB($params, $db) { //Pass array and db
$fields = array();
$conn = new mysqli('localhost', 'root', 'root', 'db') or die('XXX');
$stmt = $conn->stmt_init();
$stmt->prepare("SELECT * FROM ".$db);
$stmt->execute();
$meta = $stmt->result_metadata();
while ($field = $meta->fetch_field()) {
$fields[] = $field->name;
}
$fields = implode(", ", $fields);
$placeholders = implode(',', array_fill(0, count($params), '?'));
$types = '';
foreach($params as $value) {
$types.= substr(strtolower(gettype($value)), 0, 1);
}
$ins = "INSERT INTO MYDB (".$fields.") VALUES (".$placeholders.")";
$bind_names[] = $types;
for ($i = 0; $i < count($params); $i++) {
$bind_name = 'bind' . $i;
$$bind_name = $params[$i];
$bind_names[] = &$$bind_name;
}
if ($stmt->prepare($ins)) {
call_user_func_array(array($stmt,'bind_param'),$bind_names);
$insresult = $stmt->execute();
}
return $insresult;
$stmt->close();
}