Inserting Data From a PHP Form
Posted by tutor | Posted in PHP Tutorial | Posted on 18-12-2009-05-2008
0
The most interesting part of a web application is that you can use dayabase to fill the form data and vice versa. This is the most useful part also, as it increases the user interactivity and helps is realizing many functions like filling up a form online.
<html>
<body>
<form action=”insert.php” method=”post”>
Country: <input type=”text” name=”country” />
Capital: <input type=”text” name=”capital” />
<input type=”submit” />
</form>
</body>
</html>
When a user clicks the submit button in the HTML form in the example above, the form data is sent to “AddValues.php”.
The “AddValues.php” file connects to a database, and retrieves the values from the form with the PHP $_POST variables.Then, the mysql_query() function executes the INSERT INTO statement, and a new record will be added to the “Country” table.
<?php
$con = mysql_connect(“localhost”,”tutor”,”tutor123″);
if (!$conn)
{
die(‘Could not connect: ‘ . mysql_error());
}
mysql_select_db(“my_db”, $conn);
$sql=”INSERT INTO Country (Country, Capital)
VALUES(‘$_POST[country]‘,’$_POST[capital]‘)”;
if (!mysql_query($sql,$con))
{
die(‘Error: ‘ . mysql_error());
}
echo “Record added successfully”;
mysql_close($conn)
?>
