Records being duplicated into DB

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
snapy
Forum Newbie
Posts: 4
Joined: Fri Sep 09, 2005 2:03 am

Records being duplicated into DB

Post 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
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

it would seem you have a second insert query in your code somewhere..
sheila
Forum Commoner
Posts: 98
Joined: Mon Sep 05, 2005 9:52 pm
Location: Texas

Post 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.
snapy
Forum Newbie
Posts: 4
Joined: Fri Sep 09, 2005 2:03 am

Solved

Post by snapy »

Sheila,

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

Thanks again,

matt
Post Reply