Monday, October 3, 2016

How to create simple PHP form and save to database?

Things to know:
  • Tools Required to implement this code WAMP for Windows.
  • Save this code to .php file.
  • Place that file in WWW directory. WWW directory will in c:/wamp by default.
  • Create Database in mySQL name it as "test". after that create new table name as "temp" with fields "Fname" and "Lname".

 <!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Demo</title>
</head>
<body>

<br />

<?php
if(isset($_POST['btn'])){
if($_POST['fname']==""){
echo 'Error: Insert first name';
}
else if($_POST['lname']==""){
echo 'Error: Insert last name';
}
else{
$conn = mysqli_connect('localhost','root','','test');
$str = "insert into temp (fname,lname) values('".$_POST['fname']."','".$_POST['lname']."')";
mysqli_query($conn,$str);
echo 'Inserted successfully';
}
}

echo '<br /><br />';

?>

<form action="" method="POST">
//textbox for input value 1
First Name: <input type="text" name="fname" />
<br />
<br />
//textbox for input value 2
Last Name: <input type="text" name="lname" />
<br />
<br />
//submit button to save values in database 
<input type="submit" name="btn" value="Insert" />
</html>

</body>
</html>


Output:


Post a Comment