Build a single multiple insert query from an array in PHP - php

I have an array that looks like this
$users = array(
array('name'=>'aaa','age'=>2),
array('name'=>'bbb','age'=>9),
array('name'=>'ccc','age'=>7)
);
I would like to create a function that will accept an array like above, creates a clause for a single query-multiple insert, prepares an array of variable that I can bind with PDO.
example output:
$clause = INSERT INTO tablename (`name`,`age`)
VALUES (:name_0,:age_0),(:name_1,:age_1),(:name_2,:age_2);
Then another set of array corresponding to the values above:
$params => Array
(
[name_0] => aaa
[age_0] => 2
[name_1] => bbb
[age_1] => 9
[name_2] => ccc
[age_2] => 7
);
So that the can execute it like so:
$prepared = $connection->prepare($clause);
$prepared->execute($params);
Is it possible to achieve this in a single function?

Yes that very possible, I did exactly the same thing for my custom query builder class:
function INSERT_MULTIPLE_QUERY($ARRS = array()){
$raw_cols = '(`';
// PREPARE THE COLUMNS
foreach($ARRS[0] as $key1 => $value):
$raw_cols .= $key1.'`,`';
endforeach;
$final_cols = rtrim($raw_cols,'`,`') . '`)';
$ctr1=0; $raw_vals='';
// PREPARE THE VALUES
foreach($ARRS as $ARR_VALUE):
$raw_vals .= '(';
foreach($ARR_VALUE as $key => $value): $raw_vals .= ':'.$key.'_'.$ctr1.','; endforeach;
$raw_vals = rtrim($raw_vals,',');
$raw_vals .= '),';
$ctr1++;
endforeach;
$final_vals = rtrim($raw_vals,',');
$ctr2 = 0; $param = array();
// PREPARE THE PARAMETERS
foreach($ARRS as $ARR_PARAM):
foreach($ARR_PARAM as $key_param => $value_param):$param[$key_param.'_'.$ctr2] = $value_param; endforeach;
$ctr2++;
endforeach;
// PREPARE THE CLAUSE
$clause = 'INSERT INTO tablename ' . $final_cols . ' VALUES ' . $final_vals;
// RETURN THE CLAUSE AND THE PARAMETERS
$return['clause'] = $clause;
$return['param'] = $param;
return $return;
}
Now to use this function:
$query = INSERT_MULTIPLE_QUERY($users);
// $users is your example array above
Then:
$prepared = $connection->prepare($query['clause']);
$prepared->execute($query['param']);

You can do it in a OOP style by creating a QueryBuilder and PDOStatementDecorator like below:
class QueryBuilder
{
const BUILD_TYPE_INSERT_MULTIPLE = 'INSERT_MULTIPLE';
protected $table;
protected $values;
protected $buildType;
public function __construct($table)
{
$this->table = $table;
}
public static function onTable($table)
{
return new self($table);
}
public function insertMultiple(Array $values = array())
{
$this->values = $values;
$this->buildType = self::BUILD_TYPE_INSERT_MULTIPLE;
return $this;
}
public function build()
{
switch ($this->buildType) {
case self::BUILD_TYPE_INSERT_MULTIPLE:
return $this->buildInsertMultiple();
}
}
protected function buildInsertMultiple()
{
$fields = array_keys($this->values[0]);
$query = "INSERT INTO {$this->table} (" . implode(',', $fields) . ") VALUES ";
$values = array();
for ($i = 0; $i < count($fields); $i++) {
$values[] = '(' . implode(', ', array_map(function($field) use ($i) {
return ':' . $field . $i;
}, $fields)) . ')';
}
$query .= implode(', ', $values);
return $query;
}
}
class PDOStatementDecorator
{
protected $pdoStatement;
public function __construct(PDOStatement $pdoStatement)
{
$this->pdoStatement = $pdoStatement;
}
public function executeMultiple(Array $bindsGroup = array())
{
$binds = array();
for ($i = 0; $i < count($bindsGroup); $i++) {
foreach ($bindsGroup[$i] as $key => $value) {
$binds[$key . $i] = $value;
}
}
return $this->execute($binds);
}
public function execute(Array $inputParemeters)
{
return $this->pdoStatement->execute($inputParemeters);
}
public function fetch($fetchStyle = null, $cursorOrientation = 'PDO::FETCH_ORI_NEXT', $cursorOffset = 0)
{
return $this->pdoStatement->fetch($fetchStyle, $cursorOrientation, $cursorOffset);
}
/**
* TODO
* Implement all public PDOStatement methods
*/
}
The query builder can be enhanced to be able to build queries for update/delete statements.
Now the usage would be very simple:
$users = array(
array('name' => 'aaa', 'age' => 2),
array('name' => 'bbb', 'age' => 9),
array('name' => 'ccc', 'age' => 7),
);
$query = QueryBuilder::onTable('users')->insertMultiple($users)->build();
$stmt = new PDOStatementDecorator($pdo->prepare($query));
$stmt->executeMultiple($users);

This function require Table Name, your original array, and an optional parameter that is used as default value, only if one field is not present in all array rows:
function buildQuery( $table, $array, $default='NULL' )
{
/* Retrieve complete field names list: */
$fields = array();
foreach( $array as $row ) $fields = array_merge( $fields, array_keys( $row ) );
$fields = array_unique( $fields );
/* Analize each array row, then update parameters and values chunks: */
$values = $params = array();
foreach( $array as $key => $row )
{
$line = array();
foreach( $fields as $field )
{
if( !isset( $row[$field] ) )
{ $line[] = $default; }
else
{
$line[] = ":{$field}_{$key}";
$params["{$field}_{$key}"] = $row[$field];
}
}
$values[] = '('.implode(',',$line).')';
}
/* Compone MySQL query: */
$clause = sprintf
(
"INSERT INTO `%s` (`%s`) VALUES %s;",
$table,
implode( '`,`', $fields ),
implode( ',', $values )
);
/* Return array[ clause, params ]: */
return compact( 'clause', 'params' );
}
Calling it in this way:
$query = buildQuery( 'mytable', $users );
$query will contain this:
Array
(
[clause] => INSERT INTO `mytable` (`name`,`age`) VALUES (:name_0,:age_0),(:name_1,:age_1),(:name_2,:age_2);
[params] => Array
(
[name_0] => aaa
[age_0] => 2
[name_1] => bbb
[age_1] => 9
[name_2] => ccc
[age_2] => 7
)
)
eval.in demo

Related

How to dynamically fill key and value in an associative array using for loop in PHP

$main= array(
"data"=>array(
"userid"=>"1",
"$str",
"acc_id"=>"10",
"fi"=>"3"
),
"next"=>"4"
);
Here i added
"value1"=>"$row->field1",
"value2"=>"$row->field2",
"value3"=>"$row->field3",
"value4"=>"$row->field4"
using $str Dynamically with the help of for loop because it is dynamic not fixed.
I want to make this array like the below, so it can work and print correct output - It's my desired output(I want this array like this to be working)
array(
"data"=>array(
"userid"=>"$row->uid",
"value1"=>"$row->field1",
"value2"=>"$row->field2",
"value3"=>"$row->field3",
"value4"=>"$row->field4",
"acc_id"=>"$acc_id",
"tloop"=>"$timeloopc"
),
"next"=>"$next"
);
Output is -
But array taking the value of $str as string and when i print thisit shows output -
Array (
[data] => Array (
[user1] => 1
[0] => "value1"=>"$row->field1",
"value2"=>"$row->field2",
"value3"=>"$row->field3",
"value4"=>"$row->field4",
"value5"=>"$row->field5"
[user2] => 2
[fi] => 3
)
[next] => 4
)
The Above output is issue... Here array processing some key and value but not processing $str value... it's taking it as sting.
It's now processing the $str values as string from "value1" and "field1"..to..4
Help me to dynamically fill key and value in an associative array using for loop.
In the array "value1 and field1" - here numbers are dynamic - "value2" and "field2"...
When i am making array dynamic, it's not working like array. If i make it static it works fine.
So please help me to make $str value from string to array value(object)...
Here is complete code -
<?php
$ct = 4;
$str = '';
for($cunt=1; $cunt<=$ct; $cunt++)
{
$valu= '"value';
$cuntc = $cunt.'"';
$rw = '"$row';
$fild= "field";
$cp = $valu.$cuntc."=>".$rw."->".$fild.$cuntc;
$str .= $cp . ',';
}
//trim the , from last value
$str = rtrim($str, ",");
$main= array("data"=>array("userid"=>"1","$str","acc_id"=>"10","fi"=>"3"),"next"=>"4");
print_r($main);
?>
I don't know what exactly you want.
There is a code, which build array you'd like to have:
$main= array(
"data"=>array(
"userid"=>"1",
"$str",
"acc_id"=>"10",
"fi"=>"3"
),
"next"=>"4"
);
$ct = 4;
$subArray = array();
$resultArray = array();
$resultArray['data']['userid'] = '$row->uid';
for($cunt=1; $cunt<=$ct; $cunt++)
{
$valu= 'value';
$rw = 'row';
$fild= "field";
$resultArray['data'][$valu . $cunt] = '$' . $rw . '->' . $fild .$cunt;
}
$resultArray['data']['acc_id'] = '$acc_id';
$resultArray['data']['tloop'] = '$timeloopc';
$resultArray['next'] = '$next';
echo "<pre>";
var_dump($resultArray);
echo "</pre>";
But if you don't need restricted key ordering, you can use something like this (it's rebuild $main array):
$main= array(
"data"=>array(
"userid"=>"1",
"$str",
"acc_id"=>"10",
"fi"=>"3"
),
"next"=>"4"
);
$fields = array();
for($cunt=1; $cunt<=$ct; $cunt++)
{
$valu= 'value';
$rw = 'row';
$fild= "field";
$fields[$valu . $cunt] = '$' . $rw . '->' . $fild .$cunt;
}
foreach ($fields as $key => $value) {
$main['data'][$key] = $value;
}
And there is solution with functions:
function generateFieldArray($keyName, $obj, $field, $rowCount)
{
$resultArray = array();
for($count=1; $count<=$rowCount; $count++)
{
$resultArray[$keyName . $count] = '$' . $obj . '->' . $field .$count;
}
return $resultArray;
}
function buildMainArray($inputArray, $keyName, $obj, $field, $rowCount)
{
$arrayToAdd = generateFieldArray($keyName, $obj, $field, $rowCount);
foreach ($arrayToAdd as $key => $value) {
$inputArray['data'][$key] = $value;
}
return $inputArray;
}
function buildMainArray2($inputArray, $keyName, $obj, $field, $rowCount)
{
$resultArray = array();
$resultArray['data']['userid'] = '$row->uid';
$arrayToAdd = generateFieldArray($keyName, $obj, $field, $rowCount);
foreach ($arrayToAdd as $key => $value) {
$resultArray['data'][$key] = $value;
}
$resultArray['data']['acc_id'] = '$acc_id';
$resultArray['data']['tloop'] = '$timeloopc';
$resultArray['next'] = '$next';
return $resultArray;
}
$main= array(
"data"=>array(
"userid"=>"1",
"$str",
"acc_id"=>"10",
"fi"=>"3"
),
"next"=>"4"
);
$result = buildMainArray($main, 'value', 'row', 'field', 4);
// or
$result = buildMainArray2($main, 'value', 'row', 'field', 4);

PDOStatement::execute() expects parameter 1 to be array, string given

I have this error:
PDOStatement::execute() expects parameter 1 to be array, string given
in C:\xampp\htdocs\Work\AppDarbNajah\App\Database.php on line 63
ArticleController code:
public function edit() {
$id = $_GET['ID'];
if(!empty($_POST) && (!empty($_FILES))){
$this->Article->update($id, [
'ref' => $_POST['ref'],
'desig' => $_POST['desig'],
'category_id' => $_POST['category_id'],
'tva' => $_POST['tva'],
'unit_id' => $_POST['unit_id'],
'Supplier_id' => $_POST['box-infos-id'],
'thumb' => $_FILES['thumb']['name'],
'created_by' => 2855,
'updated_by' => 2855
]);
}
$categories = $this->Category->extract('ID', 'category');
$units = $this->Unit->extract('ID', 'unit');
$tva = $this->Tva->extract('ID', 'tva (%)');
$article = $this->Article->find($id);
var_dump($article);
$form = new BootstrapForm($article);
$this->render('articles/edit',compact('form', 'categories', 'units', 'tva'));
}
Line 63 is:
'ref' => $_POST['ref']
I didn't write all code I wrote only the function that has error
update function code:
public function update($id, $fields){
$sql_pairs = [];
$attributes = [];
foreach ($fields as $k =>$v){
$sql_pairs[] = "$k = ?";
$attributes[] = $v;
}
$attributes = [];
$sql_parts = implode(', ', $sql_pairs);
$this->query("UPDATE INTO {$this->table} SET $sql_parts WHERE ID = ?", $attributes);
}
the problem was i should use array [$id] in find function as the following:
public function find($id){
return $this->query("SELECT * FROM {$this->table} WHERE ID = ?", [$id], true);
}
I am not sure about library you use to create your model but your function is weird.
public function update($id, $fields){
$sql_pairs = [];
$attributes = [];
// this bring an idea that you create list of fields to update #ref1
foreach ($fields as $k =>$v){
$sql_pairs[] = "$k = ?";
// here you add new value for next field to attributes #ref2
$attributes[] = $v;
}
// here you reset all values collected (#ref2) #ref3
// $attributes = []; //so let remove it
// but instead we need to add ID value to our query
$attributes[] = $id;
$sql_parts = implode(', ', $sql_pairs);
// UPDATE for MySQL should be something like :
// UPDATE my_table SET col1="newval1", col2="newval2" WHERE ID = 1
// lets try to get that format
$this->query("UPDATE {$this->table} SET $sql_parts WHERE ID = ?", $attributes);
}
Hope now it will work better....

Getting error with prepared statement query

I'm facing a problem for several days now, and I'm staring blind at it, and can't seem to find the source myself.
I've made a class to execute my queries. The actual query executing part looks like this:
<?php
public function query( $method, $table, $data, $where_text='', $where_data='' ) {
$this->check_db_status();
$method = strtoupper( $method );
$fieldsArray = array();
$valuesArray = array();
$paramsArray = array();
$format = '';
$queryText = '';
switch( $method ) {
case 'SELECT' :
$queryText = 'SELECT %s FROM ' . $table . ' ';
foreach( $data as $field => $value ) {
$fieldsArray[] = $value;
}
break;
case 'UPDATE' :
$queryText = 'UPDATE ' . $table . ' SET %s ';
foreach( $data as $field => $value ) {
$fieldsArray[] = $field.'=?';
$format .= $this->get_value_type( $value );
$paramsArray[] = $value;
}
break;
case 'DELETE' :
$queryText = 'DELETE FROM ' . $table . ' ';
break;
case 'INSERT' :
$queryText = 'INSERT INTO ' . $table . ' (%s) VALUES (%s) ';
foreach( $data as $field => $value ) {
$fieldsArray[] = $field;
$format .= $this->get_value_type( $value );
$valuesArray[] = '?';
$paramsArray[] = $value;
}
break;
default :
$this->get_error( 'Error in method switch' );
break;
}
if( $where_text ) {
$queryText .= $where_text;
if( $where_data ) {
foreach( $where_data as $value ) {
$format .= $this->get_value_type( $value );
$paramsArray[] = $value;
}
}
}
$fields = implode( ',', $fieldsArray );
$values = implode( ',', $valuesArray );
$query = sprintf( $queryText, $fields, $values );
// DEBUG
echo '<pre>';
echo 'query: ' . $query . '<br />
echo 'format: ' .' . $format . '<br />';
print_r( $paramsArray );
echo '</pre>';
$stmt = $this->mysqli->prepare( $query );
if( $stmt === false or $stmt == NULL ) {
$this->get_error( 'Error while preparing the statement' );
}
if( $format and $paramsArray )
call_user_func_array( 'mysqli_stmt_bind_param', array_merge( array( $stmt, $format ), $paramsArray ) );
if( $stmt->execute() ) {
$result = 0;
switch( $method ) {
case 'INSERT' :
$result = ($stmt->insert_id) ? $stmt->insert_id : true;
break;
case 'UPDATE' :
case 'DELETE' :
$result = ($stmt->affected_rows) ? $stmt->affected_rows : true;
break;
case 'SELECT' :
$meta = $stmt->result_metadata();
$fields = $result = array();
while ($field = $meta->fetch_field()) {
$var = $field->name;
$$var = null;
$fields[$var] = &$$var;
}
call_user_func_array(array($stmt,'bind_result'),$fields);
$i = 0;
while( $stmt->fetch() ) {
$result[$i] = array();
foreach( $fields as $k => $v)
$result[$i][$k] = $v;
$i++;
}
break;
}
$stmt->close();
$this->query_cnt++;
return $result;
}
else {
$this->get_error();
}
}
?>
Now I'm trying to make an other class to store my sessions in my own database. The write function looks like this:
<?php
public function write_session( $session_id, $session_data ) {
$query = $this->sql->query( 'INSERT', 'sessions', array( 'ses_id'=>$session_id, 'ses_time'=>time(), 'ses_start'=>time(), 'ses_data'=>$session_data, 'ses_check'=>$this->check ), 'ON DUPLICATE KEY UPDATE ses_time=?, ses_data=?', array(time(),$session_data));
if($query) {
return true;
}
else {
return false;
}
}
?>
I keep getting this error:
Warning: mysqli::prepare() [mysqli.prepare]: Couldn't fetch mysqli in /.../class.db.php on line 124
Line 124 is the line with $stmt = $this->mysqli->prepare( $query );. It is triggered by the first line of the write_session.
If put in a debug part in the database class to show the query, it gives this output:
query: INSERT INTO sessions (ses_id,ses_time,ses_start,ses_data,ses_check) VALUES (?,?,?,?,?) ON DUPLICATE KEY UPDATE ses_time=?, ses_data=?
format: [siissis]
Array
(
[0] => a98696a8416fc898f2c07e05f39735dc
[1] => 1402201705
[2] => 1402201705
[3] => test|s:11:"someValuess";
[4] => 40b17cb572d9bf5eaadad99b7904e0a4889a31d0
[5] => 1402201705
[6] => test|s:11:"someValuess";
)
Which seems fine to me.... what am I overlooking?
Edit
Table definition of sessions:
sessions (
ses_id varchar(32) NOT NULL,
ses_time int(11) NOT NULL,
ses_start int(11) NOT NULL,
ses_data text NOT NULL,
ses_check varchar(40) NOT NULL,
PRIMARY KEY (ses_id)
)
A pointed out in the link provided in the comments, your problem appears to be
4. You mixed OOP and functional calls to the database object.
Specifically, you use a mysqli object here
$stmt = $this->mysqli->prepare( $query );
But then proceed to make a functional mysqli call here
if( $format and $paramsArray )
call_user_func_array( 'mysqli_stmt_bind_param', array_merge( array( $stmt, $format ), $paramsArray ) );
So try replacing the code above with its corresponding OOP version
if($format and $paramsArray) {
$stmt->bind_param($format,$paramsArray);
}
Also replace
call_user_func_array(array($stmt,'bind_result'),$fields);
With
$stmt->bind_param($format,$fields);
http://www.php.net//manual/en/mysqli-stmt.bind-param.php
Implement __wakeup
Another possibility is that your db connection may have been closed due to serialization. Try reconnecting by implementing __wakup i.e.
public function __wakeup()
{
$this->mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
}

Wordpress $wpdb. Insert Multiple Records

Is there any way to accomplish the following in Wordpress with $wpdb->insert or
$wpdb->query($wpdb->prepare)):
INSERT into TABLE (column1, column2, column3)
VALUES
('value1', 'value2', 'value3'),
('otherval1', 'otherval2', 'otherval3'),
('anotherval1', 'anotherval2', 'anotherval3')
...etc
OK, I figured it out!
Setup arrays for Actual Values, and Placeholders
$values = array();
$place_holders = array();
the initial Query:
$query = "INSERT INTO orders (order_id, product_id, quantity) VALUES ";
Then loop through the the values you're looking to add, and insert them in the appropriate arrays:
foreach ( $_POST as $key => $value ) {
array_push( $values, $value, $order_id );
$place_holders[] = "('%d', '%d')" /* In my case, i know they will always be integers */
}
Then add these bits to the initial query:
$query .= implode( ', ', $place_holders );
$wpdb->query( $wpdb->prepare( "$query ", $values ) );
You can also use this way to build the query:
$values = array();
// We're preparing each DB item on it's own. Makes the code cleaner.
foreach ( $items as $key => $value ) {
$values[] = $wpdb->prepare( "(%d,%d)", $key, $value );
}
$query = "INSERT INTO orders (order_id, product_id, quantity) VALUES ";
$query .= implode( ",\n", $values );
I have came across with this problem and decided to build a more improved function by using accepted answer too:
/**
* A method for inserting multiple rows into the specified table
*
* Usage Example:
*
* $insert_arrays = array();
* foreach($assets as $asset) {
*
* $insert_arrays[] = array(
* 'type' => "multiple_row_insert",
* 'status' => 1,
* 'name'=>$asset,
* 'added_date' => current_time( 'mysql' ),
* 'last_update' => current_time( 'mysql' ));
*
* }
*
* wp_insert_rows($insert_arrays);
*
*
* #param array $row_arrays
* #param string $wp_table_name
* #return false|int
*
* #author Ugur Mirza ZEYREK
* #source http://stackoverflow.com/a/12374838/1194797
*/
function wp_insert_rows($row_arrays = array(), $wp_table_name) {
global $wpdb;
$wp_table_name = esc_sql($wp_table_name);
// Setup arrays for Actual Values, and Placeholders
$values = array();
$place_holders = array();
$query = "";
$query_columns = "";
$query .= "INSERT INTO {$wp_table_name} (";
foreach($row_arrays as $count => $row_array)
{
foreach($row_array as $key => $value) {
if($count == 0) {
if($query_columns) {
$query_columns .= ",".$key."";
} else {
$query_columns .= "".$key."";
}
}
$values[] = $value;
if(is_numeric($value)) {
if(isset($place_holders[$count])) {
$place_holders[$count] .= ", '%d'";
} else {
$place_holders[$count] .= "( '%d'";
}
} else {
if(isset($place_holders[$count])) {
$place_holders[$count] .= ", '%s'";
} else {
$place_holders[$count] .= "( '%s'";
}
}
}
// mind closing the GAP
$place_holders[$count] .= ")";
}
$query .= " $query_columns ) VALUES ";
$query .= implode(', ', $place_holders);
if($wpdb->query($wpdb->prepare($query, $values))){
return true;
} else {
return false;
}
}
Source: https://github.com/mirzazeyrek/wp-multiple-insert
In addition to inserting multiple rows using $wpdb, if you ever need to update existing rows following snippet should be helpful.
This is updated snippet of what #philipp provided above.
$values = array();
// We're preparing each DB item on it's own. Makes the code cleaner.
foreach ( $items as $key => $value ) {
$values[] = $wpdb->prepare( "(%d,%d)", $key, $value );
}
$values = implode( ",\n", $values );
$query = "INSERT INTO orders (order_id, product_id, quantity) VALUES {$values} ON DUPLICATE KEY UPDATE `quantity` = VALUES(quantity)";
This is a bit late, but you could also do it like this.
global $wpdb;
$table_name = $wpdb->prefix . 'your_table';
foreach ($your_array as $key => $value) {
$result = $wpdb->insert(
$table_name,
array(
'colname_1' => $value[0],
'colname_2' => $value[1],
'colname_3' => $value[2],
)
);
}
if (!$result) {
print 'There was a error';
}
not very nice, but if you know what you are doing:
require_once('wp-load.php');
mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
#mysql_select_db(DB_NAME) or die();
mysql_query("INSERT into TABLE ('column1', 'column2', 'column3') VALUES
('value1', 'value2', 'value3'),
('otherval1', 'otherval2', 'otherval3'),
('anotherval1', 'anotherval2', 'anotherval3)");

Modify syntax of this function to exclude several arrays instead of one

I'm a newbie to PHP and don't know how to modify the syntax of this function so that it can be used to exclude several arrays instead of only one. This code automatically INSERTS every value that's input in a form without having to specify the fields and excludes one array (called 'submit'), and is a slightly modified version of code that I found at http://www.abeautifulsite.net/blog/2007/10/inserting-an-array-into-a-mysql-database-table/
I have several arrays which are being posted that I want to exclude from my INSERT function since they are either being processed and inserted separately or trigger where the user is redirected once the form is processed.
function mysql_insert_array($db, $data, $exclude = array()) {
$fields = $values = array();
if( !is_array($exclude) ) $exclude = array($exclude);
foreach( array_keys($data) as $key ) {
if( !in_array($key, $exclude) ) {
$fields[] = "`$key`";
$values[] = "'" . mysql_real_escape_string($data[$key]) . "'";
}
}
$fields = implode(",", $fields);
$values = implode(",", $values);
if( mysql_query("INSERT INTO `$db` ($fields) VALUES ($values)") ) {
} else {
return array( "mysql_error" => mysql_error() );
}
}
$result = mysql_insert_array("db", $_POST, "submit");
The exclude argument could be an array of array:
function mysql_insert_array($db, $data, $excludes = array()) {
$fields = $values = array();
if( !is_array($excludes) ) $excludes = array($excludes);
foreach($excludes as $exclude ) {
$data = array_diff_assoc($data, $exclude);
}
foreach( array_keys($data) as $key ) {
$fields[] = "`$key`";
$values[] = "'" . mysql_real_escape_string($data[$key]) . "'";
}
$fields = implode(",", $fields);
$values = implode(",", $values);
if( !mysql_query("INSERT INTO `$db` ($fields) VALUES ($values)") ) {
return array( "mysql_error" => mysql_error() );
}
}
Then, you could use it like this :
$array1 = array('toto', 'titi', 'tata');
$array2 = array('submit', 'foo');
$parent_array = array ($array1, $array2);
$result = mysql_insert_array("db", $_POST, $parent_array);

Categories