This example gives a demo to insert records in mysql database table using html form in php application.
PHP MySQL Record Insert Using Form Example:
This example gives a demo to insert records in mysql database table using html form in php application.
First of all create a database using create database statement like:
CREATE DATABASE php_mysql;
After that create table using create "user" table statement like:
CREATE TABLE user( user_id int(11) NOT NULL auto_increment, user_name varchar(20) default NULL, user_email varchar(50) default NULL, user_address varchar(150) default NULL, PRIMARY KEY (user_id) )
After that we will run this example for insert record using form. In this example we will used POST method for form submission.
Example:
<?php $connection = mysql_connect("localhost","root","root"); if (!$connection) { die('PHP Mysql database connection could not connect : ' . mysql_error()); } else{ $db_name = "php_mysql"; mysql_select_db($db_name, $connection); if(isset($_POST['submit'])){ if($_POST['user_name']!="" && $_POST['user_email']!="" && $_POST['user_address']!=""){ $sql = "insert into user(user_name, user_email, user_address) values('".$_POST['user_name']."', '".$_POST['user_email']."', '".$_POST['user_address']."');"; mysql_query($sql, $connection); printf("Last inserted record has id %d\n", mysql_insert_id()); } } } ?> <html> <body> <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"> <table> <tr> <td>User Name : </td> <td><input type="text" name="user_name" /></td> <td></td> </tr> <tr> <td>Email : </td> <td><input type="text" name="user_email" /></td> <td></td> </tr> <tr> <td>Address : </td> <td><input type="text" name="user_address" /></td> <td></td> </tr> <tr> <td></td> <td><input type="submit" name='submit' value="Submit"/></td> <td></td> </tr> </table> </form> </body> </html>
After running this example the output is:
Output:
After form submission the browser output is
And the database user table output is:
[ 0 ] Comments