Page 1 of 1

Arrays, Variables, and SQL

Posted: Wed Feb 19, 2003 7:32 pm
by moniarde
I have 2 elements - the first, a variable ($sql), will become an SQL statment to insert into a database, the other ($formarray) is an array where $key= the names of a form, as well as the fields in the database, and $value= the values of said form elements. Using foreach I want to populate $sql with an Insert Set statment, but I need to specify the opening phrase of the SQL statement ("INSERT INTO table_n SET ") without repeating it each time.

Here's what I have:

Code: Select all

<?php
foreach ($formarray as $key => $value) {
	$output = "$key = '$value',";
	echo $output;
}
?>
I want to put the output of that into the middle of an SQL statement. Also I don't want the last line to include a comma at the end, or the SQL won't work.
Any ideas?

Posted: Wed Feb 19, 2003 8:26 pm
by Stoker

Code: Select all

<?php

# Using SET syntax (which is more common for UPDATE's than inserts

$comma = '';
$sql = 'INSERT INTO tablename SET ';
foreach ($formarray as $key => $value) {
   $sql .= $comma ." $key = '".mysql_escape_string($value)."' ";
   if (!$comma) $comma = ',';  # Perhaps this is more efficient by just skipping the if (?)
}

?>

Posted: Wed Feb 19, 2003 10:30 pm
by moniarde
Thanks heaps Stoker. However, I'm relatively new to PHP, and so I was hoping you that wouldn't mind explaining it to me. I specifically don't understand the use of $comma, though I get know what it's supposed to achieve, and the syntax of your $sql line.

Posted: Thu Feb 20, 2003 12:20 am
by Stoker
$comma is set to an empty string at first, so no comma is used before the first col='val' then in the loop, if comma does not resolve to true (any empty string or a zero resolves to false), it is set to ',' so that it will add the comma before the next col='val'..

$var .= ' hey';

is the same as

$var = $var . 'hey';