Is there a better way to insert values to MySQL query than just VALUES($var1, $var2, $var3)?

Go To StackoverFlow.com

1

I just have the array of 15 values that all need to be inserted into the table. And I was just wondering if there is anything like this:

INSERT INTO table VALUES($myarrayofvalues)

Just curious, would be very useful.

Update:
Just one row with 15 columns.

2012-04-05 02:29
by Serge Vinogradov
Do you want to insert 1 row with 15 columns, or 15 rows of one column - Sergio Tulentsev 2012-04-05 02:31


3

$query = "INSERT INTO table VALUES('" . implode("', '", $myarrayofvalues) . "')";

Edit:

If you haven't done your escaping yet, you can do that in a tiny loop before the above statement, something like:

foreach($myarrayofvalues as $k=>$v)
    $myarrayofvalues[$k] = mysql_real_escape_string($v);
2012-04-05 02:36
by Rick
Consider SQL Injection - Jason McCreary 2012-04-05 02:38
@Jason Always a concern, yes. This answer is just relative to the title, which has no prevention. No clue on where the vars or array come from, right? It could already be done. If not, then in this case it would have to be done before the query line, as far as I know, but would be iterable, which I think keeps the benefit the OP is looking for - Rick 2012-04-05 02:42


0

While you can do what's show in the answer by Rick, it is open to SQL injection.

There is really no good way to do this without some kind of column mapping. That is something to state element 1 is a string, element 2 is an integer.

As such, I see two choices:

  1. Escape everything

    $values = array();
    foreach ($myarrayofvalues as $value) {
      $column[] .= "'" . mysql_real_escape_string($value) . "'";
    }
    $sql = "INSERT INTO table VALUES(" . implode(',', $values) . ")";
    
  2. Write the complete SQL statement

    $sql = "INSERT INTO table (column1_string, column2_int, ...)
      VALUES ('" . mysql_real_escape_string($myarray[0]) . "', " . (int)$myarray[1] . ", ...)
    

I prefer #2 because it is more readable and less brittle. Currently if your schema or array changes, your code breaks.

2012-04-05 02:41
by Jason McCreary
Ads