Re: confused big time
| From: | Mark Ackroyd | Date: | Wed, 07 Apr 2004 16:16:04 +0000 |
| Subject: | Re: confused big time | ||
| References: | 1 2 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-182669@lists.php.net to get a copy of this message | ||
I always found this way of inserting data into a database messy. Here is a handy function to do array inserts and it builds the sql for you.
function arrayINSERT($a,$tablename)
{
$sql = "INSERT INTO $tablename (";
foreach($a as $key => $value)
{
$sql .= $key .",";
}
$sql[strlen($sql)-1] = ')';
$sql .= " VALUES (";
foreach($a as $key => $value)
{
if (gettype($value) == 'string')
{
$sql .= "'". addslashes($value) ."',";
}
else
{
$sql .= $value .",";
}
}
$sql[strlen($sql)-1] = ')';
return $sql;
}
if you do this :
$a['field1'] = $blah;
$a['field2'] = $here;
$a['field3'] = $etc;
$sql = arrayINSERT($a,"tablename");
it builds the sql statement for you. It covers 99.9% of the inserts your likely to need. I use an update and insert function like this all the time. :-)
Mark
Richard Davey wrote:
$sql = " INSERT INTOtablename ( field1, field2, field3 )VALUES( '$blah', $here', '$etc' )";