insert data from array to DB - php

I know that this theme is very common, but i'm stuck and can't find an error.
I created an array in PHP:
$dataarray=array("FECHAS" => date("Y-m-d"),"HORAS" => date("H:i:s"),
"RGD" => 0,"RGA" => 0,"FLU" => 0,"DD2" => 0,
"H2O" => 0,"PRES:U" => 0,"U" => 0,"V" => 0,"TS" => 0,
"T1" => 0,"T2" => 0,"H1" => 0,"H2" => 0, "HS" => 0,
"VV1" => 0,"VV2" => 0);
and i've got a table in MYSQL with the same names, but when i try to put data into it, it does nothing.
for($j=0;$j<$variable_para_base;$j++)
{
$keys;
$vars;
foreach($dataarray[$j] as $k=>$v)
{
$keys.= $k.',';
$vars.= $v.",";
}
echo $keys."<br>";
echo $vars."<br>";
mysqli_query($mysqli,'INSERT INTO ff ( .$keys.) VALUES ( .vars. ) ') or die(mysql_error());
unset($keys);
unset($vars);
}
if i do it with die option it does for only once another way my key starts to have strange values in the end of it.
Any ideas, and again sorry for maybe a repeted question. I get access to DB because it doesn't give me any error, though noow i'm doubting :(.

You have syntax promlems in your query.
INSERT INTO ff ( .$keys.) VALUES ( .vars. ) '
change it to
INSERT INTO ff ( '.$keys.') VALUES ( '.$vars.') '
Also you need to add ' to the varialbles inserted as VALUES.
like that:
$vars.= "'".$v."',";
In addition your last variable is also ending with , and it shouldn't be.

So your end result might look something like this:
<?
for($j=0;$j<$variable_para_base;$j++)
{
$keys = array();
$vars = array();
foreach($dataarray[$j] as $k=>$v)
{
$keys[] = $k;
$vars[] = $v;
}
$placeholders = array_fill(0, count($keys), '?'); //used to fill a number of '?' needed to fill later
//here we use the '?' array to be placeholders for the values
$query = "INSERT INTO ff (".implode(', ', $keys).") VALUES (".implode(', ', $placeholders).")"; //implode the arrays and separate by comma
$statement = $mysqli->prepare($query);
$types = array(str_repeat('s', count($vars))); //get the number of parameters and put the 's' to it (used for string values)
$values = array_merge($types, $vars); //merge the arrays (gets you {'s', $value})
call_user_func_array(array($statement, 'bind_param'), $values); //bind the values to the statement
$result = $statement->execute(); //execute.
if($result) {
print "Array inserted, worked like a charm.";
}
else {
print "I failed, sorry...". $mysqli->error();
}
unset($keys);
unset($vars);
}
$statement->close();
?>
This is however untested so test it good.
References you can use:
Stackoverflow question: PHP - MySQL prepared statement to INSERT an array
Stackoverflow question: Best way to INSERT many values in mysqli
Stackoverflow question: Mysqli insert command

You can not insert a array directly to mysql as mysql doesn't understand php data types. Mysql only understands SQL. So to insert this array into a mysql database you have to convert it to an sql statement. This can be done manually or by a library. The output should be an INSERT statement.
Here is a standard mysql insert statement.
INSERT INTO TABLE1(COLUMN1, COLUMN2, ....) VALUES (VALUE1, VALUE2..)
If you have a table with name fbdata with the columns which are presented in the keys of your array you can insert with this small snippet. Here is how your array is converted to this statement.
$columns = implode(", ",array_keys($insData));
$escaped_values = array_map('mysql_real_escape_string', array_values($insData));
$values = implode(", ", $escaped_values);
$sql = "INSERT INTO `fbdata`($columns) VALUES ($values)";

you have error in query try this,
mysqli_query($mysqli,'INSERT INTO ff (' .$keys. ') VALUES (' .$vars. ') ') or die(mysql_error());

Related

Insert associative PHP arrays into mysql without typing every individual insert name and value

This is my first time asking a question so sorry if I am unclear. My goal is to have an html form create an associative array ($_Session) and then have that array submitted to a MySQL database table. My $_Session array is going to get very long so I was wondering if there is a way to submit the array where the keys are the MySQL table column names and the values are inserted under the column name.
I am aware that I can code something similar to
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
but my issues with that is I would have to type out each insert name and value. Could there possibly be a foreach loop to go through the array and insert everything without having to type out each individual key to the array?
Here's how you can do this using mysqli prepared statements, which will help protect you if any of the variable data comes from the internet. Note that every mysqli statement has error checking so if this isn't exactly right for your environment you should quickly see where the issue is.
$_SESSION = ["firstname" => "John", "lastname" => "Doe", "email" => "john#example.com", "age" => 24] ;
// create the query
$sql = "INSERT INTO MyGuests (" .
implode(',', array_keys($_SESSION)) .
') VALUES (' .
implode(',', array_fill(0, count($_SESSION), '?')) .
')';
echo $sql;
// prepare the query (assuming mysqli, connection $conn)
$stmt = $conn->prepare($sql) or die($conn->error);
// prepare the variable types for the bind
$types = '';
foreach ($_SESSION as $value) {
if (is_int($value)) $types .= 'i';
elseif (is_numeric($value)) $types .= 'd';
else $types .= 's';
}
// need to get the values into a numerically indexed array for the splat operator
$values = array_values($_SESSION);
$stmt->bind_param($types, ...$values) or die($conn->error);
$stmt->execute() or die($stmt->error);
Note that if the keys of the $_SESSION array are derived from user input, you still need to check that they are valid to completely protect yourself from SQL injection. The ideal way to do that would be to compare them against a list of the actual column names in MyGuests.
To do what you want we can use array_walk (or just a regular foreach loop) to process each key-val pair.
We take care to add enclosing "" around string values.
Finally, we can use the INSERT INTO ... SET structure to easily get what we want into the query (rather than INSERT INTO ... VALUES).
<?php
$_SESSION = ["firstname" => "John", "lastname" => "Doe", "email" => "john#example.com", "age" => 24] ;
// we "accumulate" the result in $arr
array_walk($_SESSION, function($v, $k) use (&$arr) {
// add quotes around strings
$val = is_numeric($v)?$v:"\"$v\"";
$arr[] = "$k = $val";
});
$list = implode(", ", $arr);
$query = "INSERT INTO MyGuests SET $list";
echo $query; //INSERT INTO MyGuests SET firstname = "John", lastname = "Doe", email = "john#example.com", age = 24
Demo Code
Word of warning: you shouldn't trust any input from the internet. At the very least, you need to ensure that every key in $_SESSION is a valid column name, and you need to make every value safe against SQL-injection.

Array mysql insert using array_implode with different datatype

Hi i been trying to inserting array's into MySql database
The problem i am having is that i have different datatypes and sometime data can be a 0 value, having () curly brackets, percentage value with % sign. I would like to know a way use some already built php function that can deal with this issues.
So here is what i have done so far:
$t = array('country_code' => $data->country_code,
'Name' => $data->Name,
'money' => $data->money,
'chanceToDie' => $data->death,
'age' => $cb->age)
/* FORMAT EXAMPLE
country_code = Africa (AF)
name = jack
chanceToDie = 5.5
age = 62
*/
$columns = implode(", ",array_keys($t));
//Tried
$values = implode(", ",array_values($t)); //Dont work
$values = "'".implode("', '",array_values($t))."'"; //Dont work
$sql = "INSERT INTO table ($columns) VALUES ($values)";
You need to quote each individual value and use array_values() instead of array_keys():
$values = '"' . implode('", "', array_values($t)) . '"';
However, this leaves you with an sql injection problem so you should really use a prepared statement.
In PDO you could use something like (assuming you control the keys and they are safe to use):
$values = ':' . implode(', :', array_keys($t));
// generates: ... VALUES(:country_code, :Name, :money, // etc
Now you can prepare and execute your query using the array to bind the values to the placeholders. See for example http://php.net/manual/en/pdo.prepared-statements.php (the 6th example).
Try to use the advantage of PDO prepared queries - it is more safe and convinient.
Your code may look like this:
$col_names = array_keys($t);
// filter column names before inserting to sql to prevent sql injection
array_filter($col_names, function($v){return preg_relace("#\W#", "_", $v);});
// generate placeholders list: ?,?,?,?
$placeholders = implode(',', array_fill(0, count(t), "?"));
$values = array_values($t);
$q = $pdo->prepare('insert into (' . implode(",", $col_names) . ') values (' . $placeholders . ')');
$q->execute($values);
PDO will deal with data types and correctly replace every placeholder with the corresponding value.

How to prepend colon (:) and append (,) array values in php?

I am trying to create simple PDO mysql insert query statement in most clean and efficient way.
My question is that, is there any simple function in php that could both append and prepend array values and convert it to a string like implode() function do? Or am i doing it right-(See last working code i provided)
Correct me if i am wrong, implode just adds a single string inbetween each value before converting to a string.Hope my code will clear out more what i am trying to achieve.
//key as field name value as value
$field_values=array(
"firstname"=>$fname,
"lastname"=>$lname,
"phone"=>$phone);
//field name would work fine as just a comma is appended to each array key
//i need,if there is an inline way to perform array values to start with colon and end with comma.
//this doesn't work as not comma is added inbetween
$sql="INSERT INTO student (".implode(",",array_keys($field_values).") VALUES (".implode(":",$field_values).")";
//result wrong no commas
//INSERT INTO student (firstname,lastname,phone) VALUES (:firstname:lastname:phone);
//i want this
//INSERT INTO student (firstname,lastname,phone) VALUES (:firstname,:lastname,:phone);
i can't use this too
$sql="INSERT INTO student (".implode(",",array_keys($field_values).") VALUES (?,?,?);
i am using this to bind
foreach($field_values as $field=>$value)
{
$dbh->bindValue(':'.$field,$value);
}
I know i could achieve this with just writing a string like :firstname,:lastname,:phone or may be with regex or use a foreach loop to append and prepend like this.This would work fine but its lengthy
$fv="";
foreach($field_values as $field=>$value)
{
$fv.=":".$field.",";
}
$fv=rtrim($fv, ",");
$sql="INSERT INTO student (".implode(",",$field_values).") VALUES (".$fv.")";
But what i want to know whether there is a way to do that something like the code i used above. in the scenario the array keys may change, so i am searching for a dynamic efficient way.
Help me please :)
Any help is appreciated.
Thank you in advance.
This PDO Insert function will accept an array as input.
// Insert an array with key-value pairs into a specified MySQL database table.
function pdo_insert($dbh,$table,$keyvals) {
$sql = sprintf("INSERT INTO %s ( `%s` ) %sVALUES ( :%s );",
$table,
implode("`, `", array_keys($keyvals)),
implode(", :", array_keys($keyvals))
);
$stmt = $dbh->prepare($sql);
foreach ($keyvals as $field => $value) {
$stmt->bindValue(":$field", $value, PDO::PARAM_STR);
}
$stmt->execute();
return $dbh->lastInsertId();
}
// Convert special characters to HTML safe entities.
function h($str) {
return trim(stripslashes(htmlspecialchars($str, ENT_QUOTES, 'utf-8')));
}
Example:
$dbh = new PDO($dsn);
$dbh->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$keyvals = [
'id' => isset($_POST['id']) ? h( $_POST['id'] ) : null,
'title' => isset($_POST['title']) ? h( $_POST['title'] ) : null,
'description' => isset($_POST['description']) ? h( $_POST['description'] ) : null,
'created_at' => time(),
'created_by' => 1,
];
$last_ids[] = pdo_insert($dbh,'products',$keyvals);
if you dont want to use a foreach to add in the : for the column names you can try something like this
$fname = "first";
$lname = "last";
$phone = "2342344";
$field_values=array(
"firstname"=>$fname,
"lastname"=>$lname,
"phone"=>$phone
);
echo "INSERT INTO student (`:".implode("`,:`",$field_values)."`) VALUES (".$fv.")";
as you can see in the insert columns i added a `: to the being and end in the columns bracket

How to insert data into MySql using an associative array [duplicate]

This question already has an answer here:
Mysqli prepared statements build INSERT query dynamically from array
(1 answer)
Closed 8 months ago.
I am now having a problem inserting data in associative array with its key as fields in the table and the values to be inserted into MySql database. Here is my code.
<?php
$table = 'articles';
$data = array(
'title' => 'Header',
'content' => 'This is content',
'author' => 'James');
$keys = implode(', ', array_keys($data));
$values = implode(', ', array_values($data));
$sql = 'insert into '.$table.'('.$keys.') values ('.$values.')';
$db = new mysqli('localhost', 'root', 'root', 'blog');
$db->query($sql);
?>
With this code, I wasn't able to insert the data into the database so I try to echo the query string out and I got something like this :
insert into articles(title, content, author) values (Header, This is content, James)
However, if I use the single quote in each value like this
insert into articles(title, content, author) values ('Header', 'This is content', 'James')
I can successfully insert the data into the database.
So I don't know what's wrong here. Is it a problem with the quote sign or not because when I use the single quote, this seems to work.
So please help me find the proper solution for this...
For the query you need to enclose each value in quotes. To do that you can change your implode statement to include the quotes to around the values -
$values = "'" .implode("','", array_values($data)) . "'";
EXAMPLE-demo
You should also be checking for errors.
Replace $db->query($sql);
with
if(!$result = $db->query($sql)){
die('There was an error running the query [' . $db->error . ']');
}
else{
echo "Data inserted.";
}
So I don't know what's wrong here. Is it a problem with the quote sign or not because when I use the single quote, this seems to work.
Yes, you need to use the single quote.
You can check it out:
$values = implode(', ', array_values($data));
Into something like it:
$values = implode (',', array_map (
function ($z)
{
return ((is_numeric ($z) || (is_string ($z) ? ($z == "NOW()" ? true : false) : false) || (is_array ($z)?(($z=implode(";",$z))?false:false):false)) ? $z : "'" . utf8_decode ($z) . "'");
}, array_values ($data)));
The idea is that you make every value field quoted, I meant value field by value field in the query. For instance, in my example, the function ignores NOW() as string, and keep it up to work as SQL's timestamp. Because if you treat it as string type, the command wouldn't work properly.
Anyway, the above is ugly and insecure.
I would advice you to look for some ORM like RedBeanORM or, maybe, use the proper PHP MySQL version like MySQLi. Mainly to avoid SQL injections.
Look one ORM example:
require 'rb.php';
R::setup();
$post = R::dispense('post');
$post->text = 'Hello World';
$id = R::store($post); //Create or Update
$post = R::load('post',$id); //Retrieve
R::trash($post); //Delete
Look one PHP MySQL improved version example:
$stmt = mysqli_prepare($link, "INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)");
mysqli_stmt_bind_param($stmt, 'sssd', $code, $language, $official, $percent);
$code = 'DEU';
$language = 'Bavarian';
$official = "F";
$percent = 11.2;
mysqli_stmt_execute($stmt);
Good luck. Good learning.
Positional place-holders:
$values = implode(', ',
array_fill(0, count($data), '?')
);
// insert into articles(title, content, author) values (?, ?, ?)
Named place-holders:
$values = implode(', ', array_map(
function($value){
return ":$value";
},
array_keys($data)
));
// insert into articles(title, content, author) values (:title, :content, :author)
Not necessarily the nicest or best code.
As about the parameter array itself, I'm not familiar with mysqli but with many DB extensions you could use $data as-is.

How to use MySQLi prepared statements to execute multiple INSERTs with variable number of placeholders?

Any ideas about how to use MySQLi prepared statements to execute multiple INSERTs while having variable number (around 40) of placeholders?
I know how to make prepared statements with variable number of placeholders:
array_unshift($paramValues, str_repeat('s', count($paramValues)));
call_user_func_array(
[$statement, 'bind_param'],
sql::makeValuesReferenced($paramValues)
);
I also know how to make multiple executions:
$statement->bind_param('i', $id);
for ($id=0, $id<10, ++$id) {
$statement->execute();
}
But I couldn't wrap my mind enough to combine both methods into single one.
Basically, I have array full of data which I want to INSERT into database without having to manualy hardcode variables. I want function where I put array with data and function will take care of binding and executing.
$data = [
0 => [a => aaa, b => bbb],
1 => [a => ccc, b => ddd],
];
(I am using PHP 5.5 and MySQL 5.5.)
Quite simply you prepare the sql once and then repeat the bind_param() and execute() multiple times. Although I think you already got that.
So using your example input
$data = [
0 => [a => aaa, b => bbb],
1 => [a => ccc, b => ddd],
];
.
// get a list of all the field names
// and also build the question mark list
$fields = '';
$qMarks = '';
foreach ( $data[0] as $field => $val ) {
$fields .= $field . ',';
$qMarks .= '?,';
}
rtrim($fields, ',');
rtrim($qMarks, ',');
/*
Build the datatype list:
Replace commas with nothing and ? with s
THIS WILL ONLY WORK IF YOUR DATATYPES ARE ALL THE SAME
If you also had the datatypes in your $data array this
would obviously work better, or rather be more flexible
I THINK THIS IS THE FLY IN THE OINTMENT!!
*/
$datatypes = '';
$datatypes = str_replace(array(',','?'),array('','s'),$qMarks);
$sql = "INSERT INTO TABLE table ($fields) VALUES($qMarks)";
$stmt = $db->prepare($sql);
foreach ($data as $row ) {
$params = array();
foreach ( $row as $name => $val ) {
$params[] = $val;
}
$stmt->bind_param($datatypes, $params);
$result = $stmt->execute();
if ( ! $result ) {
// You have an error, deal with it here and probably stop the loop
}
}

Categories