Forum Moderators: coopster

Message Too Old, No Replies

dynamic insert of POST data into database

         

bkeep

3:37 pm on Jun 3, 2007 (gmt 0)

10+ Year Member



I will give a little background to what I am doing.
I have two tables one with game data ie visitor team home team so on and so forth and one with team name and team id, this info is pulled into a dynamic form. I can get the data from the form ok


foreach($_POST as $key => $value){
echo "$key:$value";
}

when I echo the info it gives me the correct output

game1:7 game1id:513
game2:14 game2id:514

I have columns in the database that correspond to the form var fields What my question is is how do I get the info into the database through each iteration in one row?

This is an example I have tried and I know doesn't work


$sql = "INSERT INTO teampicks ($key) VALUES('". $value ."')";
$res = mysql_query($sql);

Any Help would be appreciated
Regards,
Brandon

phparion

5:32 am on Jun 4, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Run a foreach and make two strings of KEYS and VALUES then put them in your query rather than using one key-value pair in one query run.

e.g

$keys = '';
$vals = '';

foreach($_POST as $key => $value){

$keys .= "`" . $key . "` ,";
$vals .= "'" . $values . "' ,";
}

you will get comma at the end of each strong you can remove it with any string built in function of with a IF within the loop.

bkeep

5:25 pm on Jun 4, 2007 (gmt 0)

10+ Year Member



Thanks for the reply this is what I have and it works


foreach($_POST as $key => $value){

$keystr .= "$key,";
$valstr .= "'" . $value . "' ,";
}
//strip last comma
$keys = substr($keystr, 0, -1);
$vals = substr($valstr, 0, -1);

$sql = "INSERT INTO teampicks ($keys) VALUES($vals)";
$res = mysql_query($sql);

Regards,
Brandon