Jump to content

Sending form output more than once to mysql


Kiwii

Recommended Posts

So. i've made a really simple form (learning the basics of mysql + php) to send someones name and age into one table and name and favourite food into another. It works but the only trouble is that it sends it four times. Like i'll press submit and then the information will appear in the database multiple times.

 

Anyway, this is the html form code:

<form action="sent.php" method="get">
Forename: <input type="text" name="fname" /><br/>
Age: <input type="text" name="age" /><br/>
Favourite Food: <input type="text" name="fav_food" /><br/>
<input type="submit" value="Submit to database"/>
</form> 

 

and this is the php:

<?php 

mysql_connect("localhost", "admin", "1admin") 
or die(mysql_error());
mysql_select_db("test") 
or die(mysql_error());

$name = $_GET['fname'];
$age = $_GET['age'];
$fav_food = $_GET['fav_food'];

mysql_query("INSERT INTO example (name, age) VALUES('$name', '$age') ")
or die(mysql_error());  

mysql_query("INSERT INTO example2 (name, fav_food) VALUES('$name', '$fav_food') ")
or die(mysql_error());  

   echo 'Added '.$name.' who is '.$age.' and loves ' .$fav_food. ' to the database.';
?>

 

Oh and i have mysql 5.1.36 and php 5.3.0

 

Thankyou

CREATE TABLE IF NOT EXISTS `example` (

  `id` int(11) NOT NULL AUTO_INCREMENT,

  `name` varchar(30) DEFAULT NULL,

  `age` int(11) DEFAULT NULL,

  KEY `id` (`id`)

) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

 

CREATE TABLE IF NOT EXISTS `example2` (

  `id` int(11) NOT NULL AUTO_INCREMENT,

  `name` varchar(30) DEFAULT NULL,

  `fav_food` varchar(50) DEFAULT NULL,

  KEY `id` (`id`)

) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

yeah i'm sure i'm only pressing it ones, i've done it many times.

 

i'm sure if i add a script to make it check if the name and age already exists it will only input it onces but i can't think of that script.

i tried a few times but just got errors, what you think?

you can add an index on 'name' to make sure a name will only be entered once

 

alter table example add unique (name);

 

a next attempt to enter an already existing name will result in an error:

 

ERROR 1062 (23000): Duplicate entry .......

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.