--- Cditty <[EMAIL PROTECTED]> wrote:
> A co-worker is teaching me to move to the next level
> in php. I have started using associative arrays for my
> scripts, but I am having a problem using them to do an
> insert into MySQL. Can someone give me an example of
> how to do an insert to the database using these arrays?
> My array is this...$item['itemID']

Using arrays is easy. For example:

$sql = "insert into blah (foo) values('";
$sql .= $item['item_id'];
$sql .= "')";

It isn't necessary for that to span three lines, but my
mail client will annihilate it otherwise. Just use
concatenation (.) to make things easy on yourself instead
of embedding your variable in the string (possible with
curly braces).

Of course, if you want to do it the cool way (which is what
your co-worker probably wants), look at Mr. Kimsal's
example:

--- michael kimsal <[EMAIL PROTECTED]> wrote:
> <?
> $x['name'] = "Mike's";
> $x['phone'] = 'fsdlfksdf';
> echo sql($x);
> 
> function sql($a) {
>   $k = implode(",",array_keys($a));
>   array_walk($a,'slashadd');
>   $v = "'".implode("','",$a)."'";
>   return "insert into ($k) values ($v)";
> }
> function slashadd(&$bar) { $bar = addslashes($bar); }
> ?>

The only problem here is that there is no table name, which
is easily remedied. You probably want to pass the table
name as another argument. Also, use "replace into" for an
elegant way to insert the record if it does not exist
(based on whether your where clause matches) or update the
record if it does. Mr. Kimsal mentioned later in his
explanation I believe.

You can eliminate the slashadd() function and the
array_walk() call if you make sure your values are properly
escaped. If magic_quotes is on, you definitely want to
avoid the extra slashes, and it might be worth checking
whether it is on in your script, so that you don't depend
on any specific PHP configuration.

Finally, since this only builds your SQL statement, you can
enhance your function to execute the query for you (you
might want to add another argument for the database name)
and return true or false indicating success or failure.

Have fun, and tell your co-worker hello.

Chris

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to