-   Programming (
-   -   PHP Array to Tuple: Is there a built-in php function that does this? (

rm_-rf_windows 04-17-2012 08:18 AM

PHP Array to Tuple: Is there a built-in php function that does this?
Hey all,

I have a php program, an unconventional research NLP program, and in my program it would be useful to take an array which contains all of the attributes of a specific table in the form of key (attribute names) value (attribute values). I'm using static classes and passing info around...

Does anybody know if it's possible, from such an array, in a few lines, to insert the tuple into a corresponding table?

The following doesn't exist, and I know I could make my own function which does this, but this is what I'd like:
PHP Code:


Are there any built-in functions that do this or that would make it easier than to build my own function from scratch?

People usually do this going the other way of course, using mysql_query and mysql_fetch_array... I'm trying to do just the opposite. That is, not to go from $query to $result and to $row, but rather $row (a php array) to insertion into a MySQL table.

Thanks in advance,

P.S. - One of the problems in making such a function is distinguishing between strings and values requiring quotes, and other values...

Guttorm 04-17-2012 08:44 AM


It's not difficult to write such a function. Quotes doesn't matter - they're mandatory for strings and ignored for things like numerical values. It should be something like this:

PHP Code:

function array_to_mysql_tuple($array$table_name)
$sql "INSERT INTO `$table_name` SET ";
$first true;
    foreach (
$array as $key => $value) {
        if (
$first) {
$first false;
        } else {
$sql .= ",";
$sql .= "`$key` = '".mysql_real_escape_string($value)."'";

Edit: The mysql_real_escape_string function protects against SQL injection of values, but the keys need to be protected as well. So you need to check for invalid characters in the keys.

rm_-rf_windows 04-17-2012 09:16 AM

Too cool Guttorm!!

I had started working on a huge function (well, not huge, but fairly complicated and not very elegant) using "DESCRIBE table" in order to distinguish between strings and numerical values... and then I saw your swift reply.

Many thanks, this thread is resolved and closed!!


kelso.b 04-18-2012 06:25 PM

A slightly more elegant solution:


function array_to_mysql_tuple($array, $table_name)
    array_walk($array, 'mysql_real_escape_string');
    $sql = "INSERT INTO `$table_name` (`%s`) VALUES ('%s')";
    return sprintf($sql, implode('`, `', array_keys($array)), implode("', '", $array));

All times are GMT -5. The time now is 04:49 AM.