Getting error with prepared statement query - php

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');
}

Related

Is this a insecure way to use prepared statements in a php class?

I made this Class with the function query():
This function makes it really easy to use prepared statements.
But
It is secure?
Make it even sense to use it like that?
I already tested it with sqlmap and it looks good.
The function basicly split the normal SELECT string into multiple smaller string to dedect the input values.
It save the input values and the string itself.
The string itself will be replaced by ?.
Than the normal prepare function replaces the ? again with the input values.
class dbcon
{
public $con;
public function __construct()
{
$this->con = new mysqli( $host, $username, $password, $dbname );
}
public function query( $query )
{
//selcet
if( strpos( $query, "SELECT" ) !== false )
{
$types = ""; $to_replace = []; $values = [];
$query = explode( "WHERE", $query );
$query_where = explode( "ORDER BY", $query[ '1' ] );
$query_where[ '0' ];
if( isset( $query_where[ '1' ] ) )
{
$ORDERBY = explode("LIMIT", $query_where[ '1' ]);
}
if( isset( $ORDERBY[ '1' ] ) )
{
$LIMIT = $ORDERBY[ '1' ];
}
$SELECT = $query[ '0' ];
$where = str_replace( array( "(", ")", "[", "]" ), "", $query_where[ '0' ] );
$where = str_replace( array( "AND", "OR", "and", "or" ), "-|-", $where );
$where = explode( "-|-", $where );
for ($i=0; $i < count($where); $i++) {
$for_where = str_replace( array( "!=", "<=", ">=", "=", "<>", ">", "<", "IS", "NOT LIKE", "LIKE" ), "#|#", $where[ $i ] );
$for_where = explode( "#|#", $for_where );
$value = trim( $for_where[ '1' ] );
if( substr_count($value, "AND") <= 0 AND substr_count($value, "OR") <= 0 )
{
$value = "'?'";
}
$to_replace[] = $value;
$value_num = "values".$i;
$$value_num = $value;
$values[] = &$$value_num;
$types .= "s";
}
$WHERE = str_replace( $to_replace , " ? ", $query_where[ '0' ] );
$prepare = $SELECT . " WHERE " . $WHERE;
if ( isset( $ORDERBY ) )
{
$prepare .= " ORDER BY " . $ORDERBY[ '0' ];
}
if ( isset( $LIMIT ) ){
$prepare .= " LIMIT " . $LIMIT;
}
$stmt = $this->con->prepare( $prepare );
//$stmt->bind_param($types, $values['0'],$values['1']);
call_user_func_array( array( $stmt, "bind_param" ), array_merge( array( $types ), $values ) );
$stmt->execute();
return $stmt->get_result();
$stmt->close();
}
}
}
$db = new dbcon();
Call the function:
$id = $_GET[ 'id' ];
$my_query = $db->query("SELECT * FROM Users WHERE ID = '$id' ORDER BY created DESC");
while($row = $my_query->fetch_array()){
echo $row['NAME']."<br>";
}
UPDATE:
The old function makes not a lot of sense and is not secure at all. This should be still a easy way but better.
public function query( $query, $types, $query_values )
{
$values = [];
for ($i=0; $i < count($query_values); $i++) {
$value_num = "values".$i;
$$value_num = $query_values[ $i ];
$values[] = &$$value_num;
}
$stmt = $this->con->prepare( $query );
call_user_func_array( array( $stmt, "bind_param" ), array_merge( array( $types ), $values ) );
$stmt->execute();
return $stmt->get_result();
$stmt->close();
}
call the function
$query = "SELECT * FROM _Users WHERE ID = ? ORDER BY created ASC";
$my_query = $db->query( $query, "s", array( $id ) );
while($row = $my_query->fetch_array()){
echo $row['title']."<br>";
}
You cannot by definition "prepare"/"sanitise"/understand a query after you have already interpolated values into it.
$my_query = $db->query("SELECT * FROM Users WHERE ID = '$id' ORDER BY created DESC");
So what happens here if someone attempts some SQL injection? E.g.: $id = "foo' OR '1' = '1":
SELECT * FROM Users WHERE ID = 'foo' OR '1' = '1' ORDER BY created DESC
How could any code following this possibly understand the difference between what this query was supposed to do and what it is actually doing now? It cannot. The meaning has already been altered through value injection. There's no way to fix this after the fact.

Function for PDO preapred stament not work and get error

I make 2 function with same use to take over PDO Preapred Statement, but both of not work .
Function 1 :
function doSave($array, $table) {
if (count($array) == 0) {
throw new Exception('Array cant be empty');
} else {
global $connect;
//prepare the query first
$prepare_1 = 'INSERT INTO' . ' ' . $table . ' '; //start preparing
$columns = array();
foreach ($array as $key => $value) {
$columns[] = ':' . $key; //gets all columns and add commas
}
foreach ($array as $key => $value) {
$keye[] = $key; //gets all columns and add commas
}
$keyes = implode(', ', $keye);
$column = implode(', ', $columns);
//now you can combine everything and prepare
$stmt99 = $connect->prepare($prepare_1 .'('.$keyes.')'. ' VALUES (' . $column . ')');
//remember to add the values. also test this section as its not tested
foreach ($array as $key => $value) {
$test[] = "':" . $key ."' => ". $value;
}
$tests = implode(', ', $test);
$stmt99->execute($tests);
}
}
When i insert the data i got no error and no data get insert to my database
Function 2 :
function doSave($array, $table) {
if (count($array) == 0) {
throw new Exception('Array cant be empty');
} else {
global $connect;
//prepare the query first
$prepare_1 = 'INSERT INTO' . ' ' . $table . ' '; //start preparing
$columns = array();
foreach ($array as $key => $value) {
$columns[] = ':' . $key; //gets all columns and add commas
}
foreach ($array as $key => $value) {
$keye[] = $key; //gets all columns and add commas
}
$keyes = implode(', ', $keye);
$column = implode(', ', $columns);
//now you can combine everything and prepare
$stmt99 = $connect->prepare($prepare_1 .'('.$keyes.')'. ' VALUES (' . $column . ')');
//remember to add the values. also test this section as its not tested
foreach ($array as $key => $value) {
$test[] = '$stmt99->bindparam('.'":' . $key .'",'. $value.'); ';
}
$tests = implode(' ', $test);
$tests;
$stmt99->execute();
}
}
i got error when use this function :
SQLSTATE[HY093]: Invalid parameter number: no parameters were bound
This How i use the function :
$array = array('categoryName' => $categoryName, 'categorySort' => $categorySort);
doSave($array, 'category');
This the source of the array :
if (!empty($_POST["categoryName"])) {
$categoryName = ($_POST["categoryName"]);
if (!preg_match("/^[a-zA-Z ]*$/",$categoryName)) {
$errMsg = "<div class='alert alert-danger text-center'><strong>Hanya boleh huruf.</strong></div>";
}
}
if ($_POST["categorySort"] == $check['categorySort']) {
$errMsg = "<div class='alert alert-danger text-center'><strong>Urutan sudah digunakan.</strong></div>";
}else{
$categorySort = ($_POST["categorySort"]);
if (!is_numeric($_POST['categorySort'])) {
$errMsg = "<div class='alert alert-danger text-center'><strong>Hanya boleh angka.</strong></div>";
}
}
What possibly go wrong from this 2 function both function for same use. Function 1 (named param) Function 2 (bindparam) ?
The following is not fully tested but displayed what I expected when I tested it using echo statements.
You should check the return value of prepare before attempting to execute the statement because it will return false if the statement failed to be prepared correctly.
function doSave( $array, $table ) {
try{
/* if you throw exceptions you should catch them!! */
if( empty( $array ) )throw new Exception('Array cant be empty');
if( empty( $table ) )throw new Exception('Table name cannot be empty');
global $connect;
/* placeholder variables */
$prepare = $columns = $values = array();
$result = false;
$table = preg_replace("#[',\.]#",'',$table);// whatever chars deemed appropriate to replace
$prepare[]="insert into `{$table}` ";
/* iterate through source array */
foreach( $array as $key => $value ) {
$columns[] = $key;
$values[ $key ] = $value;
}
$strcolumns = implode('`,`',$columns);
$strplaceholders = ':'.implode(', :',$columns);
/* append columns and placeholders */
$prepare[]="( `$strcolumns` ) values ( $strplaceholders );";
/* finalise sql statement */
$sql=implode('',$prepare);
$stmt = $connect->prepare( $sql );
if( $stmt ){
/* bind the params */
foreach( $values as $key => $value ) $stmt->bindParam( ':'.$key, $value );
/* execute the statement */
$result = $stmt->execute();
} else {
throw new Exception('Error preparing sql statement');
}
return $result;
}catch( Exception $e ){
exit( $e->getMessage() );
}
}
The assumption I made for the code was an input array like this
$t='mytable';
$a=array(
'id' => '303',
'name' => 'bob',
'size' => 'small',
'weight'=> 'heavy'
);
NOTE:
You have two functions both with the same name. How is PHP meant to know the which function you're calling?
Function 2:
foreach ($array as $key => $value) {
$test[] = '$stmt99->bindparam('.'":' . $key .'",'. $value.'); ';
}
Because you encased this in [single] quotes, this value is no longer an object method call but is just a string. This means that when you then implode this array all you're making is a longer string.
Also, because you're using single quotes, PHP will not recognise the value $stmt99 as being a PHP object reference, instead taking it literally as dollar sign, s character, t character, m character, etc....
So PDO has no values to bind into the SQL given.
Fix:
foreach ($array as $key => $value) {
$stmt99->bindparam(":" . $key , $value);
}
unset($key,$value); // always tidy up after foreach loops.
A better fix can be found exampled here

Build a single multiple insert query from an array in 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

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);

RightMove Array - Insert column tItles and values MySQL

I'm getting very stuck on something that should be very easy. I am trying to parse a .BLM file using a PHP class from http://kodegeek.wordpress.com/2010/02/20/rightmove-data-parsing-php-class/
The Class works perfectly and outputs an array like this: -
Array ( [0] => Array ( [AGENT_REF] => _70 [ADDRESS_1] => 123 Main Street [POSTCODE1] => CF12 [POSTCODE2] => 4HY [FEATURE1] => Ideal Location [FEATURE2] => Only £250 per room [FEATURE3] => Three Double Bedrooms ) [2] => Array ( [AGENT_REF] => _83 [ADDRESS_1] => 45 Harriet Street [POSTCODE1] => CF24 [POSTCODE2] => 4BU [FEATURE1] => Modern [FEATURE2] => Laminate Flooring ) )
Once the array is created I want to immediately insert the array into a SQL table. Ideally this would grab the Field titles eg. [AGENT_REF] [ADDRESS_1] and create columns and insert the data as a new row per array ([0] => Array [2] => Array) etc.
I have tried something like this and a multitude of other variation and I cant seem to get it to work.
function mysql_insert_array($table, $rmdata) {
foreach ($rmdata as $field=>$value) {
$fields[] = '`' . $field . '`';
$values[] = "'" . $value . "'";
}
$field_list = join(',', $fields);
$value_list = join(', ', $values);
$query = "INSERT INTO testarray (" . $field_list . ") VALUES (" . $value_list . ")";
<?php
$rmdata = ARRAY();
$rmdata[0]['field1'] = 1;
$rmdata[0]['field2'] = 'two';
$rmdata[0]['field3'] = 3;
$rmdata[0]['field4'] = NULL;
$rmdata[0]['field5'] = 'five';
$rmdata[1] = $rmdata[2] = $rmdata[3] = $rmdata[0];
foreach ($rmdata AS $key => $dummy) {
$fields = ARRAY();
$values = ARRAY();
foreach ($rmdata[$key] as $field=>$value) {
if (!isset($value)) {
//$value='';
// or
//if($field=='field4') { $value=4; }
// or $values[] = "NULL";
}
if (isset($value)) {
$fields[] = $field;
$values[] = "'".$value."'";
}
}
// if (count($fields) > 0)
echo 'key: '.$key.'<br />';
$sql_fields = implode(',', $fields);
$sql_values = implode(',', $values);
print_r($sql_fields); echo '<br />';
print_r($sql_values); echo '<hr />';
}
?>
You must create table with the field list before insert.
If you dont have table created, you can use :
$sql = "CREATE TABLE if not exists TABLENAME (
id tinyint(4) unsigned NOT NULL auto_increment,
AGENT_REF varchar(80) NOT NULL,
ADDRESS_1 varchar(255),
POSTCODE1 varchar(6),
POSTCODE2 varchar(6),
FEATURE1 varchar(255),
FEATURE2 varchar(255),
FEATURE3 varchar(255),
PRIMARY KEY (id)
)";
mysql_query($sql,$link);
and after your function.
$rmdata = ARRAY();
$rmdata['field1'] = 1;
$rmdata['field2'] = 'two';
$rmdata['field3'] = 3;
$rmdata['field4'] = NULL;
$rmdata['field5'] = 'five';
$fields = ARRAY();
$values = ARRAY();
foreach ($rmdata as $field=>$value) {
if (!isset($value)) {
//$value='';
// or
//if($field=='field4') { $value=4; }
// or $values[] = "NULL";
}
if (isset($value)) {
$fields[] = $field;
$values[] = "'".$value."'";
}
}
// if (count($fields) > 0)
$sql_fields = implode(',', $fields);
$sql_values = implode(',', $values);

Categories