Re: combine implode() and array_keys() to get a string of key names

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Dave M G wrote:
> PHP List,
> 
>    I've got a series of associative arrays that contain simple string
> values that I want to insert into my database.
> 
>    In each array, the names of the keys correspond to the column names
> in the database table. The values stored in the array are, of course,
> the values that I want to insert into the columns.
> 
>    So, I want to set up a function where I can pass the array as an
> argument, and it will construct the MySQL statement using the keys for
> column names, and array values for insert  values.
> 
>    Within the function, the query looks like this:
>    $query = "INSERT INTO table (" . $columns . ") VALUES = (" . $values
> . ")";
> 
>    Assuming that the array argument passed to the function is called
> $array, converting the array values to the insert values is pretty easy:
>    $values = implode(", ", $array);
> 
>    But in the case of using the array keys for column names, it's not so
> easy:
>    $columns = implode(", " array->keys($array));
> 
>    I know that code above doesn't work, because, as described in the
> manual, array keys returns a list of the numerical indexes along with
> the string indexes. Something like this:
> 
> Array
> (
>    [0] => column1
>    [1] => column2
>    [2] => column3
> )
> 
>    At least, that's what it looks like if it's just echoed out.
> 
>    Is there a way I can strip out the relevant column names to be more
> like this:
> 
> "column1, column2. column3"
> 
>    Thank you for any advice.

I'll assume you 'data' array only contains associative keys for simpilicity,
here we go:

function davesMakeValueSafeForDBInsertionFunc($v)
{
	if (is_null($arg)) return 'NULL';
        if (is_numeric($arg)) return $arg;

	return "'".mysql_real_escape_string($arg)."'";
}

function davesFunkyDBElementQuoterFunc($elName)
{
	return "`{$elName}`";
}

$data  = array(
	'col1' => 1,
	'col2' => null,
	'col3' => "yadda yadda",
);

$columns = join(',', array_map('davesFunkyDBElementQuoterFunc', array_keys($data)));
$values  = join(',', array_map('davesMakeValueSafeForDBInsertionFunc', $data));
$query   = "INSERT INTO table ($columns) VALUES ($values)";

// tada!

> 
> -- 
> Dave M G
> 

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux