Page 1 of 1

Records being duplicated into DB

Posted: Mon Sep 12, 2005 8:54 pm
by snapy
Hello all,

I have a page which processes the POST values from a form. it inserts the data into my DB,
when I check the DB after an insert, the last record is duplicated.
Here is my code:

Code: Select all

<?
//Connect to the db
									$conn = pg_pconnect("dbname=footytips user= password=");
									if (!$conn) {
    									echo "An error occured.\n";
    											exit;
									}
									
								
foreach ( $_POST as $key => $value )
{
   // get first char. of $key, if it's 'w', then we've got tips
   if ( substr( $key, 0, 1) == 'w' )
   {
       //to test outputs from array
       print_r($_POST)	;
       
			 
       $game = (int) substr ( $key, 1 ); // get number
       $round = 1;
       $team = $value;
   		echo 'pick:'.$team.' game '.$game.' round: '.$round.'<br />';
   }
   $insert=pg_query($conn, "INSERT INTO tips(round,game_id,team_id) VALUES('".$round."','".$game."','".$team."')") OR DIE(pg_last_error());
} 

?>
I put the print_r in there to see what comes out of the array from the previous page and this is what it says:

Array ( [w2] => 1 [w3] => 10 [w4] => 4 [Submit] => submit ) pick:1 game 2 round: 1
Array ( [w2] => 1 [w3] => 10 [w4] => 4 [Submit] => submit ) pick:10 game 3 round: 1
Array ( [w2] => 1 [w3] => 10 [w4] => 4 [Submit] => submit ) pick:4 game 4 round: 1

the pick, game and round bits are just the echo that is also in there.

Here is a copy of the DB records:
footytips=# SELECT * from tips;
round | game_id | margin | team_id
-------+---------+--------+---------
1 | 2 | | 1
1 | 3 | | 10
1 | 4 | | 4
1 | 4 | | 4

Can anyone tell me where the duplicate record is comming from?

Thank you in advance,

Matt

Posted: Mon Sep 12, 2005 9:04 pm
by feyd
it would seem you have a second insert query in your code somewhere..

Posted: Mon Sep 12, 2005 9:30 pm
by sheila
The 'for' loop runs four times, once for each POST'd variable (w2, w3, w4 and Submit).
Move the insert inside the 'if' block.

Solved

Posted: Mon Sep 12, 2005 9:42 pm
by snapy
Sheila,

thank you that's fixed it. And thankyou feyd.

Thanks again,

matt