Arrays, Variables, and SQL

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
moniarde
Forum Newbie
Posts: 20
Joined: Thu Feb 06, 2003 12:45 am
Location: Perth, Western Australia

Arrays, Variables, and SQL

Post 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?
User avatar
Stoker
Forum Regular
Posts: 782
Joined: Thu Jan 23, 2003 9:45 pm
Location: SWNY
Contact:

Post 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 (?)
}

?>
User avatar
moniarde
Forum Newbie
Posts: 20
Joined: Thu Feb 06, 2003 12:45 am
Location: Perth, Western Australia

Post 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.
User avatar
Stoker
Forum Regular
Posts: 782
Joined: Thu Jan 23, 2003 9:45 pm
Location: SWNY
Contact:

Post 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';
Post Reply