php push 2d array into mysql - php

Hay All,
I cant seem to get my head around this dispite the number to examples i read. Basically I have a 2d array and want to insert it into MySQL. The array contains a few strings.
I cant get the following to work...
$value = addslashes(serialize($temp3));//temp3 is my 2d array, do i need to use keys? (i am not at the moment)
$query = "INSERT INTO table sip (id,keyword,data,flags) VALUES(\"$value\")";
mysql_query($query) or die("Failed Query");
Thanks Guys,

Not sure it's be a full answer to your question, but here at least a couple of possible problems :
You should not use addslashes ; instead, use mysql_real_escape_string
It knows about the things that are specific to your database engine.
In your SQL query, you should not use double-quotes (") arround string-values, but single-quotes (')
In your SQL query, you should have as many fields in the values() section as you have in the list of fields :
Here, you have 4 fields : id,keyword,data,flags
but only one value : VALUES(\"$value\")
You should use mysql_error() to know what was the precise error you've gotten while executing the SQL query
This will help you find out the problems in your queries ;-)

<?php
// let's assume we have a 2D array like this:
$temp3 = array(
array(
'some keywords',
'sme data',
'some flags',
),
array(
'some keywords',
'sme data',
'some flags',
),
array(
//...
),
);
// let's generate an appropriate string for insertion query
$aValues = array();
foreach ($temp3 as $aRow) {
$aValues[] = "'" . implode("','", $aRow) . "'";
}
$sValues = "(" . implode("), (", $aValues) . ")";
// Now the $sValues should be something like this
$sValues = "('some keywords','some data', 'someflags'), ('some keywords','some data', 'someflags'), (...)";
// Now let's INSERT it.
$sQuery = "insert into `my_table` (`keywords`, `data`, `flags`) values $sValues";
mysql_query($sQuery);

As an addition to the useful answers already given, if you have a big table that you need to insert it might not fit in one SQL statement. However, making a separate transaction for each row is also slow. In that case, we can tell MySQL to process multiple statements in one transaction, which will speed up the insertion greatly for big tables (>1000 rows).
An example:
<?php
function dologin() {
$db_username = 'root';
$db_password = 'root';
$db_hostname = 'localhost';
$db_database = 'logex_test';
mysql_connect($db_hostname, $db_username, $db_password);
mysql_select_db($db_database);
}
function doquery($query) {
if (!mysql_query($query)) {
echo $query.'<br><br>';
die(mysql_error());
}
}
function docreate() {
doquery("drop table if exists mytable");
doquery("create table mytable(column1 integer, column2 integer, column3 integer)");
}
function main() {
$temp3 = array(
array('1','2','3',),
array('4','5','6',),
array('7','8','9',),
);
dologin();
docreate();
doquery("start transaction");
foreach($temp3 as $row)
doquery("insert into mytable values('" . implode("','", $row) . "')");
doquery("commit") or die(mysql_error());
}
main();
?>

Try this :
// lets array
$data_array = array(
array('id'=>1,'name'=>'a'),
array('id'=>2,'name'=>'b'),
array('id'=>3,'name'=>'c'),
array('id'=>4,'name'=>'d'),
array('id'=>5,'name'=>'e')
)
;
$temp_array = array_map('implode', $data_array, array('","' ,'","','","','","','","'));
echo $query = 'insert into TABLENAME (COL1, COL2) values( ("'.implode('"),("', $temp_array).'") )';
mysql_query($query);

Related

SQL INSERT function with PHP only

edit I changed the code to the suggestion answer, all snippets now updated
currently I am playing around with PHP. Therefore I am trying to build a programm which can execute SQL commands. so, what I am trying is to write some functions which will execute the query. But I came to a point where I coundn't help myself out. My trouble is, for the INSERT INTO command, I want to give an array, containing the Data that shall be inserted but I simply can't figure out how to do this.
Here is what I got and what I think is relevant for this operation
First, the function I want to create
public function actionInsert($data_values = array())
{
$db = $this->openDB();
if ($db) {
$fields = '';
$fields_value = '';
foreach ($data_values as $columnName => $columnValue) {
if ($fields != '') {
$fields .= ',';
$fields_value .= ',';
}
$fields .= $columnName;
$fields_value .= $columnValue;
}
$sqlInsert = 'INSERT INTO ' . $this->tabelle . ' (' . $fields . ') VALUES (' . $fields_value . ')';
$result = $db->query($sqlInsert);
echo $sqlInsert;
if ($result) {
echo "success";
} else {
echo "failed";
}
}
}
and this is how I fil the values
<?php
require_once 'funktionen.php';
$adresse = new \DB\Adressen();
$adresse->actionInsert(array('nachname'=>'hallo', 'vorname'=>'du'));
My result
INSERT INTO adressen (nachname,vorname) VALUES (hallo,du)failed
What I wish to see
success
and of course the freshly insertet values in the database
There are a few things to consider when you are working with relational databases without using PDO:
What is the database that you are using.
It's your decision to choose from MySQL, postgreSQL, SQLite and etc., but different DBs generally have different syntax for inserting and selecting data, as well as other operations. Also, you may need different classes and functions to interact with them.
That being said, did you checkout the official manual of PHP? For example, An overview of a PHP application that needs to interact with a MySQL database.
What is the GOAL you are trying to accomplish?
It's helpful to construct your SQL first before you are messing around with actual codes. Check if your SQL syntax is correct. If you can run your SQL in your database, then you can try to implement your code next.
What's the right way to form an SQL query in your code?
It's okay to mess around in your local development environment, but you should definitely learn how to use prepared statements to prevent possible SQL injection attacks.
Also learn more about arrays in PHP: Arrays in PHP. You can use key-value pairs in a foreach loop:
foreach ($keyed_array as $key => $value) {
//use your key and value here
}
You don't need to construct your query in the loop itself. You are only using the loop to construct the query fields string and VALUES string. Be very careful when you are constructing the VALUES list because your fields can have different types, and you should add double quotes around string field values. And YES, you will go through all these troubles when you are doing things "manually". If you are using query parameters or PDO or any other advanced driver, it could be much easier.
After that, you can just concatenate the values to form your SQL query.
Once you get more familiar with the language itself and the database you are playing with, you'll definitely feel more comfortable. Good luck!
Is this inside of a class? I assume the tabelle property is set correctly.
That said, you should correct the foreach loop, that's not used correctly:
public function actionInsert($data_values) //$data_values should be an array
{
$db = $this->openDB();
if ($db) {
foreach ($data_values as $data){
// $data_values could be a bidimensional array, like
// [
// [field1=> value1, field2 => value2, field3 => value3],
// [field1=> value4, field2 => value5, field3 => value6],
// [field1=> value7, field2 => value8, field3 => value9],
// ]
$fields = Array();
$values = Array();
foreach($data as $key => $value){
array_push($fields,$key);
array_push($values,"'$value'");
}
$sqlInsert = 'INSERT INTO ' . $this->tabelle . ' (' . join(',',$fields) . ') VALUES (' . join(',',$values) . ')';
$result = $db->query($sqlInsert);
echo $sqlInsert;
if ($result) {
echo "success";
} else {
echo "failed";
}
}
}
This is a rather basic approach, in which you cycle through you data and do a query for every row, but it isn't very performant if you have big datasets.
Another approach would be to do everything at once, by mounting the query in the loop and sending it later (note that the starting array is different):
public function actionInsert($data_values) //$data_values should be an array
{
$db = $this->openDB();
if ($db) {
$vals = Array();
foreach ($data_values['values'] as $data){
// $data_values could be an associative array, like
// [
// fields => ['field1','field2','field3'],
// values => [
// [value1,value2,value3],
// [value4,value5,value6],
// [value7,value8,value9]
// ]
// ]
array_push('('.join(',',"'$data'").')',$vals);
}
$sqlInsert = 'INSERT INTO ' . $this->tabelle . ' (' . join(',',$data_values['fields']) . ') VALUES '.join(' , ',$vals);
$result = $db->query($sqlInsert);
echo $sqlInsert;
if ($result) {
echo "success";
} else {
echo "failed";
}
}
By the way dragonthought is right, you should do some kind of sanitizing for good practice even if you don't make it public.
Thanks to #Eagle L's answer, I figured a way that finally works. It is diffrent from what I tryed first, but if anyone having similar troubles, I hope this helps him out.
//get the Values you need to insert as required parameters
public function actionInsert($nachname, $vorname, $plz, $wohnort, $strasse)
{
//database connection
$db = $this->openDB();
if ($db) {
//use a prepared statement
$insert = $db->prepare("INSERT INTO adressen (nachname, vorname, plz, wohnort, strasse) VALUES(?,?,?,?,?)");
//fill the Values
$insert->bind_param('ssiss', $nachname, $vorname, $plz, $wohnort, $strasse);
//but only if every Value is defined to avoid NULL fields in the Database
if ($vorname && $nachname && $plz && $wohnort && $strasse) {
edited
$inserted = $insert->execute(); //added $inserted
//this is still clumsy and user unfriendly but serves my needs
if ($inserted) {//changed $insert->execute() to $inserted
echo 'success';
} else {
echo 'failed' . $inserted->error;
}
}
}
}
and the Function call
<?php
require_once 'funktionen.php';
$adresse = new \DB\Adressen();
$adresse->actionInsert('valueWillBe$nachname', 'valueWillBe$vorname', 'valueWillBe$plz', 'valueWillBe$wohnort', '$valueWillBe$strasse');

I'm Unable to perform a PHP insert query

I'm trying to insert the data in a MYSQL database but it seems that my query is not working i've tried all other methods but nothing is working for me ,Here is the PHP that i'm using
<?php
$server="localhost";
$database="hospital";
$login="root";
$password="";
$connexion=mysql_connect ($server, $login, $password) or die ('Server cannot be found'.mysql_error ( ));
mysql_select_db ($database,$connexion)or die ('database cannot be found'.mysql_error( ));
$a= mysql_real_escape_string($_POST['doctorname']);
$b = mysql_real_escape_string($_POST['writtendate']);
$c = mysql_real_escape_string($_POST['hospitalname']);
$d = mysql_real_escape_string($_POST['patientname']);
$e = mysql_real_escape_string($_POST['dateofbirth']);
$f= mysql_real_escape_string($_POST['cardnumber']);
$g = mysql_real_escape_string($_POST['groupname']);
$h = mysql_real_escape_string($_POST['drug1']);
$i = mysql_real_escape_string($_POST['drug2']);
$j = mysql_real_escape_string($_POST['drug3']);
$k = mysql_real_escape_string($_POST['drug4']);
$l = mysql_real_escape_string($_POST['amount1']);
$m = mysql_real_escape_string($_POST['amount2']);
$n = mysql_real_escape_string($_POST['amount3']);
$f = mysql_real_escape_string($_POST['principalmembersname']);
if(#$_POST['submit'])
{
$query="insert into uap(doctorname,writtendate,hospitalname,patientname,dateofbirth,cardnumber,groupname,principalmembersname,drug1,drug2,drug3,drug4,amount1,amount2,amount3) values ('$_POST[doctorname]','$_POST[writtendate]','$_POST[hospitalname]','$_POST[patientname]','$_POST[dateofbirth]','$_POST[cardnumber]','$_POST[groupname]','$_POST[principalmembersname]','$_POST[drug1]','$_POST[drug2]','$_POST[drug3]','$_POST[drug4]','$_POST[amount1]','$_POST[amount2]','$_POST[amount3]')";
$answer=mysql_db_query ($database, $query);
}
mysql_close ($connexion);
?>
To get you on the right track on using PDO and prepared statements (with named placeholders in this case):
<?php
$pdo = new PDO('mysql:host=localhost;dbname=databasename', 'username', 'password');
$statement = $pdo->prepare("INSERT INTO `uap` (`doctorname`,`writtendate`,`hospitalname`,`patientname`,`dateofbirth`,`cardnumber`,`groupname`,`principalmembersname`,`drug1`,`drug2`,`drug3`,`drug4`,`amount1`,`amount2`,`amount3`) VALUES (:doctorname, :writtendate, :hospitalname, :patientname, :dateofbirth, :cardnumber, :groupname, :principalmembersname, :drug1, :drug2, :drug3, :drug4, :amount1, :amount2, :amount3)");
$result = $statement->execute(
array(
'doctorname' => $_POST['doctorname'],
'writtendate' => $_POST['writtendate'],
'hospitalname' => $_POST['hospitalname'],
'patientname' => $_POST['patientname'],
'dateofbirth' => $_POST['dateofbirth'],
'cardnumber' => $_POST['cardnumber'],
'groupname' => $_POST['groupname'],
'principalmembersname' => $_POST['principalmembersname'],
'drug1' => $_POST['drug1'],
'drug2' => $_POST['drug2'],
'drug3' => $_POST['drug3'],
'drug4' => $_POST['drug4'],
'amount1' => $_POST['amount1'],
'amount2' => $_POST['amount2'],
'amount3' => $_POST['amount3']
)
);
if (!$result)
{
echo "SQL Error <br/>";
echo $statement->queryString."<br/>";
echo $statement->errorInfo()[2];
}
Although I still think your schema could use some optimization (eg. a dedicated drug table with a many-to-many relation to patients or whatever this is)
The problem with the code that you have above mainly lies in string concatenation. In your $query variable you have two primary issues:
First you have combined array syntax within a quoted string:
$query = "insert into uap (...) values ('$_POST[doctorname]')"
Second the when you reference arrays like $_POST[doctorname] (without the quotes around the keys) PHP assumes that the unquoted string is a constant that contains the same value as its name. That makes this seem like proper code, but it is actually very, VERY messy.
The PHP interpreter cannot understand exactly what you are trying to do in this case and ends up stopping concatenation at the $_POST variable. So your resultant string probably looks something like this: insert into uap (...) values ('array[doctorname]'). You can correct this by using braces to tell the PHP interpreter to use the whole array syntax in the string:
$query = "insert into uap (...) values ('{$_POST['doctorname']}')" or by using the concatenation . operator to perform proper string concatenation: $query = 'insert into uap (...) values ('".$_POST['doctorname']."')".
You simplest solution however, is to use the variables that you had specified above in your code. You final $query variable should look something like this (which will also use the `mysql_escape_string() function that you used above):
<?php
$server="localhost";
$database="hospital";
$login="root";
$password="";
$connexion=mysql_connect ($server, $login, $password) or die ('Server cannot be found'.mysql_error ( ));
mysql_select_db ($database,$connexion)or die ('database cannot be found'.mysql_error( ));
$doctorname = mysql_real_escape_string($_POST['doctorname']);
$writtendate = mysql_real_escape_string($_POST['writtendate']);
$hospitalname = mysql_real_escape_string($_POST['hospitalname']);
$patientname = mysql_real_escape_string($_POST['patientname']);
$datofbirth = mysql_real_escape_string($_POST['dateofbirth']);
$cardnumber = mysql_real_escape_string($_POST['cardnumber']);
$groupname = mysql_real_escape_string($_POST['groupname']);
$drug1 = mysql_real_escape_string($_POST['drug1']);
$drug2 = mysql_real_escape_string($_POST['drug2']);
$drug3 = mysql_real_escape_string($_POST['drug3']);
$drug4 = mysql_real_escape_string($_POST['drug4']);
$amount1 = mysql_real_escape_string($_POST['amount1']);
$amount2 = mysql_real_escape_string($_POST['amount2']);
$amount3 = mysql_real_escape_string($_POST['amount3']);
$principlemembersname = mysql_real_escape_string($_POST['principalmembersname']);
if(#$_POST['submit'])
{
$query = "insert into uap(doctorname,writtendate,hospitalname,patientname,dateofbirth,cardnumber,groupname,principalmembersname,drug1,drug2,drug3,drug4,amount1,amount2,amount3)
values ('$doctorname','$writtendate','$hospitalname','$patientname','$datofbirth','$cardnumber','$groupname','$principlemembersname','$drug1','$drug2','$drug3','$drug4','$amount1','$amount2','$amount3')";
$answer=mysql_db_query ($database, $query);
}
mysql_close ($connexion);
?>
As noted by other users it would be a good idea to convert this code to use PDO and prepared statements as the mysql functions in PHP are deprecated.
Good luck! I hope this helps!

Why decomposing associative array changes somehow previously stored picture?

Let's read the image file into varialble picture:
$picture = addslashes(fread(fopen($image, "r"), filesize($image)));
This $picture you can easy insert into database table with no trouble.
*for example*: INSERT INTO $banners(banner) VALUES( $picture );
For some reason lets create an associative array $final:
$final["banner"] = $picture;
$final["place"] = something...
Later lets decompose $final and insert the obtained values into database:
$fields = ""; $values = "";
while (list($name, $value) = each( $final ))
{
$fields .= "$name, ";
$values .= "'$value', ";
}
// Cut trailing commas
$values_fields = ereg_replace(", $", "", $values_fields);
$values = ereg_replace(", $", "", $values);
// Execute query
$query = "INSERT INTO banners($values_fields) VALUES($values)";
$res = mysql_db_query($database, $query) or mysql_die();
Now MySQL warns "Something wrong" when comes to insert consecutive $value with $picture into database. Why?
First, don't destroy your data. Read it directly and keep the variable clean:
$picture = file_get_contents($image);
Next, prepare the data for insertion:
$final["banner"] = mysqli_real_escape_string($picture);
$final["place"] = $something;
Last, there is no need to loop through your array, since it only contains one record. You don't quote the values, causing an error.
$fields = "`" . implode("`, `", array_keys($final)) . "`";
$values = "'" . implode("', '", array_values($final)) . "'";
$query = "INSERT INTO banners ({$fields}) VALUES ({$values})";
$result = mysqli_query($database, $query) or die(mysqli_error($database));
I'm using MySQLi here, since the mysql_* functions are deprecated (as well as ereg_* functions).
If the code you posted here is exactly the one you are trying to run then please note that you are accumulating field names in $fields variable but "cut trailing commas" from $values_fields which is at this point empty. Putting empty $values_fields into your query might be the cause of mysql error.
Why are you doing addslashes()? Try to use mysql_real_escape_string() instead.
Also make sure that the type of the database column where you are trying to put your image into is BLOB or LONGBLOB.
You may find answer to this question Binary Data in MySQL relevant.

mysql data insertion with foreach loop

I was inserting records successfully with this code:
foreach($R as $k=>$v)
{
$test_id = str_replace('rep_result_', '', $k);
if(strstr($k, 'rep_result_'))
{
$content = $v;
$SQL = "INSERT INTO report SET
rep_te_id = '$test_id',
rep_result = '$content',
record_id = '$R[payment_id]',
rep_date = '$dt'";
But now I have two extra fields in my table, remark and nor. So now, for inserting all data I made this code:
foreach($R as $k=>$v)
{
$test_id = str_replace('rep_result_', '', $k);
if(strstr($k, 'rep_result_'))
{
$content = $v;
if(strstr($k, 'remark_'))
{
$remark=$v;
if(strstr($k, 'nor_'))
{
$nor=$v;
$SQL = "INSERT INTO report SET
rep_te_id = '$test_id',
rep_result = '$content',
record_id = '$R[payment_id]',
remark = '**$remark**',
nor = '**$nor**',
rep_date = '$dt'";
I did not get anything in the database. Not everything is ok here. If I use only one if condition then data is being inserted like (rep_result,remark,nor any one).
if(strstr($k, 'remark_'))
$remark=$v;
But when I use all the three condition, nothing is stored. I know I have ifstatement or foreach loop problem.
As others have said, your SQL syntax is fundamentally incorrect (mixing INSERT and UPDATE syntax). A single row insert statement would have a structure like this:
INSERT INTO report (rep_te_id, rep_result, record_id, rep_date )
VALUES ( '$test_id', '$content', '$R[payment_id]', '$dt' )
Do read up on prepared statements, MySQLi and PDO to learn more about performance and efficient use of the database server.
Also, just in a general sense, sending numerous independent SQL statements to the database from within a loop is potentially a huge performance issue. There is communication and connection overhead associated with each one of those calls that has nothing to do with the actual data insertion work that you want to the database server to perform.
MySQL allows you to insert multiple rows with the same statement, so you could build up a single SQL statement in your loop, then send all the inserts in one call to the database.
The syntax to insert multiple rows with one statement looks like:
INSERT INTO report (rep_te_id, rep_result, record_id, rep_date )
VALUES ( '1', 'Row 1 content', '1', '2013-04-15' ),
( '2', 'Row 2 content', '2', '2013-04-15' ),
( '3', 'Row 3 content', '3', '2013-04-15' ),
( '4', 'Row 4 content', '4', '2013-04-15' );
For documentation and more examples, see:
http://dev.mysql.com/doc/refman/5.5/en/insert.html
https://stackoverflow.com/a/6889087/618649
https://stackoverflow.com/a/1307652/618649
Your INSERT query statment has mistakes.
I can't test your code but i assume your condition works here is a sample of mysqli connection and INSERT query.
//opening connection
$mysqli = new mysqli($dbserver, $dblogin, $dbpassword, $dbname);
if (mysqli_connect_errno())
{
printf("Connection failed: %s\n", mysqli_connect_error());
exit();
}
foreach($R as $k=>$v)
{
$test_id = str_replace('rep_result_', '', $k);
if(strstr($k, 'rep_result_'))
{
$content = $v;
if(strstr($k, 'remark_'))
{
$remark=$v;
if(strstr($k, 'nor_'))
{
$nor=$v;
$SQL = "INSERT INTO report (`rep_te_id`, `rep_result`, `record_id`, `remark`, `nor`, `rep_date`) VALUES ('".$test_id."', '".$content."', '".$R['payment_id']."', '".$remark."', '".$nor."', '".$dt."')";
echo $SQL //let's see the query
$mysqli->query($SQL) or die($msqli->error.__LINE__);
}
}
}
}
as you see i placed an echo right after the $SQL statement to see if your condition are matched. If the query will not be printed so yuo have problem with all those if condition
hey buddy your insert query syntax is wrong user correct and learn some sql query syntax
INSERT INTO report (rep_te_id,rep_result,remark,nor,rep_date) VALUES ('$test_id','$content','$R[payment_id]','**$remark**','**$nor**','$dt');
Try implement an else for each of your if condition and try echoing something from their, because look like any of your If condition is not getting satisfied.
I would suggest you to echo $k only from all three else because you will be able to know current value of $k.
also specify else no. in echo so you will be able to get which else got called.

PDO PHP insert into DB from an associative array

I have an array like this
$a = array( 'phone' => 111111111, 'image' => "sadasdasd43eadasdad" );
When I do a var-dump I get this ->
{ ["phone"]=> int(111111111) ["image"]=> string(19) "sadasdasd43eadasdad" }
Now I am trying to add this to the DB using the IN statement -
$q = $DBH->prepare("INSERT INTO user :column_string VALUES :value_string");
$q->bindParam(':column_string',implode(',',array_keys($a)));
$q->bindParam(':value_string',implode(',',array_values($a)));
$q->execute();
The problem I am having is that implode return a string. But the 'phone' column is an integer in the database and also the array is storing it as an integer. Hence I am getting the SQL error as my final query look like this --
INSERT INTO user 'phone,image' values '111111111,sadasdasd43eadasdad';
Which is a wrong query. Is there any way around it.
My column names are dynamic based what the user wants to insert. So I cannot use the placeholders like :phone and :image as I may not always get a values for those two columns. Please let me know if there is a way around this. otherwise I will have to define multiple functions each type of update.
Thanks.
Last time I checked, it was not possible to prepare a statement where the affected columns were unknown at preparation time - but that thing seems to work - maybe your database system is more forgiving than those I am using (mainly postgres)
What is clearly wrong is the implode() statement, as each variable should be handled by it self, you also need parenthesis around the field list in the insert statement.
To insert user defined fields, I think you have to do something like this (at least that how I do it);
$fields=array_keys($a); // here you have to trust your field names!
$values=array_values($a);
$fieldlist=implode(',',$fields);
$qs=str_repeat("?,",count($fields)-1);
$sql="insert into user($fieldlist) values(${qs}?)";
$q=$DBH->prepare($sql);
$q->execute($values);
If you cannot trust the field names in $a, you have to do something like
foreach($a as $f=>$v){
if(validfield($f)){
$fields[]=$f;
$values[]=$v;
}
}
Where validfields is a function that you write that tests each fieldname and checks if it is valid (quick and dirty by making an associative array $valfields=array('name'=>1,'email'=>1, 'phone'=>1 ... and then checking for the value of $valfields[$f], or (as I would prefer) by fetching the field names from the server)
SQL query parameters can be used only where you would otherwise put a literal value.
So if you could see yourself putting a quoted string literal, date literal, or numeric literal in that position in the query, you can use a parameter.
You can't use a parameter for a column name, a table name, a lists of values, an SQL keyword, or any other expressions or syntax.
For those cases, you still have to interpolate content into the SQL string, so you have some risk of SQL injection. The way to protect against that is with whitelisting the column names, and rejecting any input that doesn't match the whitelist.
Because all other answers allow SQL injection. For user input you need to filter for allowed field names:
// change this
$fields = array('email', 'name', 'whatever');
$fieldlist = implode(',', $fields);
$values = array_values(array_intersect_key($_POST, array_flip($fields)));
$qs = str_repeat("?,",count($fields)-1) . '?';
$q = $db->prepare("INSERT INTO events ($fieldlist) values($qs)");
$q->execute($values);
I appreciated MortenSickel's answer, but I wanted to use named parameters to be on the safe side:
$keys = array_keys($a);
$sql = "INSERT INTO user (".implode(", ",$keys).") \n";
$sql .= "VALUES ( :".implode(", :",$keys).")";
$q = $this->dbConnection->prepare($sql);
return $q->execute($a);
You actually can have the :phone and :image fields bound with null values in advance. The structure of the table is fixed anyway and you probably should got that way.
But the answer to your question might look like this:
$keys = ':' . implode(', :', array_keys($array));
$values = str_repeat('?, ', count($array)-1) . '?';
$i = 1;
$q = $DBH->prepare("INSERT INTO user ($keys) VALUES ($values)");
foreach($array as $value)
$q->bindParam($i++, $value, PDO::PARAM_STR, mb_strlen($value));
I know this question has be answered a long time ago, but I found it today and have a little contribution in addition to the answer of #MortenSickel.
The class below will allow you to insert or update an associative array to your database table. For more information about MySQL PDO please visit: http://php.net/manual/en/book.pdo.php
<?php
class dbConnection
{
protected $dbConnection;
function __construct($dbSettings) {
$this->openDatabase($dbSettings);
}
function openDatabase($dbSettings) {
$dsn = 'mysql:host='.$dbSettings['host'].';dbname='.$dbSettings['name'];
$this->dbConnection = new PDO($dsn, $dbSettings['username'], $dbSettings['password']);
$this->dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
function insertArray($table, $array) {
$fields=array_keys($array);
$values=array_values($array);
$fieldlist=implode(',', $fields);
$qs=str_repeat("?,",count($fields)-1);
$sql="INSERT INTO `".$table."` (".$fieldlist.") VALUES (${qs}?)";
$q = $this->dbConnection->prepare($sql);
return $q->execute($values);
}
function updateArray($table, $id, $array) {
$fields=array_keys($array);
$values=array_values($array);
$fieldlist=implode(',', $fields);
$qs=str_repeat("?,",count($fields)-1);
$firstfield = true;
$sql = "UPDATE `".$table."` SET";
for ($i = 0; $i < count($fields); $i++) {
if(!$firstfield) {
$sql .= ", ";
}
$sql .= " ".$fields[$i]."=?";
$firstfield = false;
}
$sql .= " WHERE `id` =?";
$sth = $this->dbConnection->prepare($sql);
$values[] = $id;
return $sth->execute($values);
}
}
?>
dbConnection class usage:
<?php
$dbSettings['host'] = 'localhost';
$dbSettings['name'] = 'databasename';
$dbSettings['username'] = 'username';
$dbSettings['password'] = 'password';
$dbh = new dbConnection( $dbSettings );
$a = array( 'phone' => 111111111, 'image' => "sadasdasd43eadasdad" );
$dbh->insertArray('user', $a);
// This will asume your table has a 'id' column, id: 1 will be updated in the example below:
$dbh->updateArray('user', 1, $a);
?>
public function insert($data = [] , $table = ''){
$keys = array_keys($data);
$fields = implode(',',$keys);
$pre_fields = ':'.implode(', :',$keys);
$query = parent::prepare("INSERT INTO $table($fields) VALUES($pre_fields) ");
return $query->execute($data);
}

Categories