Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Foreach insert in MySQL

56 views
Skip to first unread message

The87Boy

unread,
Apr 1, 2009, 7:02:30 AM4/1/09
to
I am trying to insert values in MySQL, where the keys from Post is the
same as the row in MySQL, but it creates an overflow
I am trying to run this code:

foreach ($pst AS $ky=>$vl) {

// Check if key is not ref, and set it into MySQL
if ($ky != 'ref') {

// Initialize the keys
$keys .= '`'.$ky.'`';

// Initialize the strings
$vals .= "'".addslashes($vl)."'";
}

// Check if it is not the end, and if it is not add ", " to the end
of the strings
if (end($pst) != $vl) {
$keys .= ', ';
$vals .= ', ';
}
}

Jerry Stuckle

unread,
Apr 1, 2009, 5:27:09 AM4/1/09
to

Well, I don't see any mysql-related code, no table descriptions and no
error messages. So it's impossible to tell what you're doing wrong.

BTW - don't use addslashes() to sanitize your data - you should be using
mysql_real_escape_string().

--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
jstu...@attglobal.net
==================

supe...@gmail.com

unread,
Apr 6, 2009, 4:12:05 PM4/6/09
to
Hi

On 1 Apr., 13:02, The87Boy <the87...@gmail.com> wrote:
> I am trying to insert values in MySQL, where the keys from Post is the
> same as the row in MySQL, but it creates an overflow

Not knowing exactly what you are trying to do, but just a little hint
with my code below. This will yield two strings in $keys and $vals
with all form names comma seperated and all form values comma
seperated. Afterwards you need to write some SQL code like stated in
my code below. I would also rather use implode() than some array end
check juggling. Is quite more understandable IMHO. HTH.

foreach ($_POST as $key => $element) {
if ($key != 'ref') {
$keys[] = mysql_real_escape_string($key);
$vals[] = mysql_real_escape_string("'$element'");
}
}

$keys = implode(',', $keys);
$vals = implode(',', $vals);

$sqlcode = "INSERT INTO table_expression ($keys) VALUES ($vals)";
mysql_query($sqlcode);

Rgds,
Greg

0 new messages