Insert values into MySQL database with HTML form and PHP

Posted by Shek on May 12, 2008 under PHP | 2 Comments to Read | Total View: 44,091 views

Editor’s note: In my past projects, especially those for company use, many of them involved with a login system and have the user name and password stored in a MySQL database. Sometime for administrators, there is a need for them to add more users when there is a new stuff for example, and therefore it is good to design an interface for them to insert the values into the MySQL database.

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:

Name:

Password:



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";}
?>

Not what you want? Try a Search

  • Upul - Sri Lanka said,

    Thanks vvvvvv much…..

    because, I tried my best to find this testing and searching the method in internet

    Now, I got it..

    Thanks again

  • Shek said,

    Thank you for your interest on my blog

Add A Comment

*