PHP-Mysql Insert by Form

on Sunday, November 11, 2012

Mysql Insert using form

For creating dynamic pages it is so important to know how data is inserted in mysql data base.

Example --à

// save as form.php or form.html
<html>
<head><title>connection through form action</title></head>
<body>
<form action=”insert.php” method=”POST”>
 //here we can use method=”GET”
//GET is use for passing variables through address bar whereas POST method doesn’t show         any pass in url or address bar.
// form fields like input box and buttons etc...
<input type=”text” id=”name” name=”name” />
<input type=”text” id=”age” name=”age” />
</form>
</body>
</html>

// save as insert.php

<?php
$host=”localhost”; // variable containing hostname
$username=”root”;  //variable having username
$password=””;
$dbname=”softfive”;
$tablename=”data”; // data is the table name in softfive database
mysql_connect("$host","$username","$password") or die("Unable to connect"); mysql_select_db("$dbname") or die("Unable to select database");
$name=$_POST[‘name’]; 
$age=$_POST[‘age’];
// receiving variable value from form.php where ‘name’ is the name of input field
$sql=INSERT INTO $tablename(Name,Age) VALUES(‘$name’,’$age’);
$queryresult=mysql_query($sql);
//passing query to variable , you can do it without passing like mysql_query($sql)
if(!qureyresult) {
echo “failed to insert please retry”;
}
else
{  echo “inserted sucessfull”;
header(‘Location:form.php’);
   }

?>

// now upload the both files to server where PHP and mysql installed and run form.php
// note: PHP is case sensitive so don’t use your own words......