php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #24132 insert an array with keyed values into a mysql table
Submitted: 2003-06-11 13:54 UTC Modified: 2003-06-13 17:19 UTC
From: wayne-php at waynef dot com Assigned:
Status: Not a bug Package: Feature/Change Request
PHP Version: 4.3.2 OS: freebsd
Private report: No CVE-ID: None
 [2003-06-11 13:54 UTC] wayne-php at waynef dot com
i have created a function i found useful. i am sure there are better ways to doing this and it doesn't do much error checking but you get the idea and how this may be a useful feature...

/**
 ** this function will take in an array with keyed values
 ** and place the values into the
 ** same name columns as the key name.
 **
 ** bool mysql_insert_array(array, table_name)
 **
 ** ie...
 **
 **      $array = array("id" => $id, "md5" => md5($id));
 **
 **      mysql_insert_array($array, "users");
 **/
function mysql_insert_array($array, $table) {

    $keys = array_keys($array);

    for ($index = 0; $index < count($array); $index++) {

        if ($index != 0) {
            $columns .= ",";
            $values .= ",";
        }

        /** construct the column names from the array **/
        $columns .= $keys[$index];

        if (is_int($array[$keys[$index]])) {
            $values .= $array[$keys[$index]];
        } else {
            $values .= "'" . mysql_real_escape_string($array[$keys[$index]]) . "'";
        }
    }

    $query = "INSERT INTO `" . $table . "` (" . $columns . ") VALUES (" . $values . ")";
    
    if (($result = mysql_query($query)) == 0)
        return(0);

    if (mysql_affected_rows() == 1)
        return(1);
    else
        return(0);
}

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2003-06-13 17:19 UTC] georg@php.net
This is too special and won't work with lot of MySQL specific column types/syntax.

MySQL-Syntax:

insert into foo (a) values (GeomFromText('point(10 10)'));
insert into foo (a,b) values ("1", a+1);

How will you realize these queries with your function? Quoting all values doesn't work.

Also you would need a lot of additional parameters for insert delayed, priority and duplicate keys.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Wed Sep 18 22:01:26 2024 UTC