How can I make a web form with drop down boxes to insert data into a relational database

Go To StackoverFlow.com

0

I'm busy trying to create a website for my football team. The thing I'm having problems with is creating a web form with drop down boxes to select and insert the match data. I'm already able to add a match in phpmyadmin where I can just select team_home and team_away, so the relational database seems to work.

I've got the following 2 tables:

Teams

  • id (pk - ai)
  • name

Matches

  • id (pk - ai)
  • date
  • team_home (foreign key -> table teams field name)
  • team_away (foreign key -> table teams field name)
  • score_home
  • score_away

So how can I make a web form with drop down boxes so I can add matches into my database?

UPDATE:

I've got the form working with drop down boxes, but I'm getting the following error when I'm submitting the form:

Error: Cannot add or update a child row: a foreign key constraint fails (roflz.matches, CONSTRAINT matches_ibfk_1 FOREIGN KEY (team_home) REFERENCES teams (name))

I've posted my submit form code and insertmatch.php code

Submit form code

$sql="SELECT id, name FROM Teams";
$result=mysql_query($sql);

$options="";

while ($row=mysql_fetch_array($result)) {

$id=$row["id"];
$name=$row["name"];
$optionshometeam.="<OPTION VALUE=\"$id\">".$name;
$optionsawayteam.="<OPTION VALUE=\"$id\">".$name;
}
?>

<form action="insertmatch.php" method="post">
<SELECT NAME=Teams>
<OPTION VALUE=0>Home Team
<?=$optionshometeam?>
</SELECT> 
<SELECT NAME=Teams>
<OPTION VALUE=0>Away team
<?=$optionsawayteam?>
</SELECT>
Score Home team: <input type="text" name="score_home" />
Score Away team: <input type="text" name="score_away" />
Match Date: <input type="text" name="score_away" />
<input type="submit" />
</form>

insertmatch.php code

mysql_select_db("roflz", $con);

$sql="INSERT INTO matches (team_home, team_away, score_home, score_away, date)
VALUES
('$_POST[team_home]','
$_POST[team_away]','
$_POST[score_home]',' 
$_POST[score_away]'
$_POST[date]')";

if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "Match added";

mysql_close($con);
?>

So what's causing this error?

Error: Cannot add or update a child row: a foreign key constraint fails (roflz.matches, CONSTRAINT matches_ibfk_1 FOREIGN KEY (team_home) REFERENCES teams (name))

2012-04-04 16:35
by Johan
You will need to create an html page, probably with a form element in it--though you could use ajax if you are comfortable with javascript. Do you have any code yet - AlexMA 2012-04-04 16:48
I don't have any code yet because I simply have no idea where to start. I know how to make a basic drop down box in html, but the options should be retrieved from the teams table - Johan 2012-04-04 17:05
You can create the page but use PHP variables instead of static text for your option and write those