Insert values into MySQL database with HTML form and PHP
To insert values such as user name and password into the MySQL database, a HTML form and PHP could do the job, here is an example I made to show how to do so:
I have created a table named “test” with 2 fields, 1 named “name” and the other 1 named “password”.
I have created 2 files, one is the HTML form file named “insertform.html”, the other one is the PHP file named “insert.php”.
Here are the codes of the “insertform.html”:
HTML Form creation here. The form has 3 HTML form elements – 2 text fields and a submit button, one text field named “user”, the other text field named “userpassword”.
<html> <form method="post" name="input" action="insert.php" > Name:<br/> <input name="user" type="text"/><br/> Password:<br/> <input name="userpassword" type="text"/> <input type="submit" name="Submit" value="insert" /> </form> </html>
The HTML form:
Here are the codes of the “insert.php”:
First we have to connect to database:
mysql_connect("Host Name", "User Name", "User Password") or die("Connection Failed"); mysql_select_db("DataBase Name")or die("Connection Failed");
Then we create 2 PHP variables to hold the 2 values from the 2 text fields of the HTML form.
$user = $_POST['user']; $password = $_POST['userpassword'];
Now we create the query for inserting the 2 values into the MySQL database table, remember to single quote ‘ ‘ the PHP variables.
$query = "INSERT INTO test(name,password)VALUES('$user','$password')";
We run the query with the “mysql_query( )” PHP function and to check whether they have been inserted successfully, I have put an “if” condition statement there to echo out the result.
if(mysql_query($query)){ echo "inserted";} else{ echo "fail";}
All together for insert.php:
<?php mysql_connect("Host Name", "User Name", "User Password") or die("Connection Failed"); mysql_select_db("DataBase Name")or die("Connection Failed"); $user = $_POST['user']; $password = $_POST['userpassword']; $query = "INSERT INTO test(name,password)VALUES('$user','$password')"; if(mysql_query($query)){ echo "inserted";} else{ echo "fail";} ?>
Similar Posts:
- MD5 – insert an encrypted string or password to the MySQL database with HTML form and PHP
- Insert multiple lines from textarea of HTML Form into MySQL database with PHP
- Update a MySQL database field data with HTML form and PHP
- Create check box by using the records from MySQL datebase as values
- Delete records from MySQL database with HTML form and PHP





