Update a MySQL database field data with HTML form and PHP
There are 2 files for the demonstration: “updateform.html” and “update.php”.
A table with 2 fields is created in the MySQL database, I named the table “test”. “name” and “password” for the 2 fields.
“tom” and “abc” have inserted in the fields “name” and “password” of the MySQL database respectively.
The goal of this demonstration how to update the password “abc” to “def”.
Here are the codes:
For “updateform.html”:
A HTML form with 2 text fields and one submit button is created here. User has to input the name into the “name” text field of which the password of that person needs to change. The new password has to input into the “password” text field. When the submit button is clicked, the form will direct us to the “update.php” file.
<html> <form method="post" name="update" action="update.php" /> Name: <input type="text" name="user" /> Password: <input type="text" name="userpassword" /> <input type="submit" name="Submit" value="update" /> </form> </html>
Name:
Password:
For “updateform.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 updating the password values of the “password” field where the “name” field is equal to “$user”.
$query = "UPDATE test SET password = '$password' WHERE name = '$user'";
Now we run the query with the “mysql_query( )” PHP function and to check whether they have been updated successfully, I have put an “if” condition statement there to see if the query runs successfully.
if(mysql_query($query)){ echo "updated";} else{ echo "fail";}
All together for update.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 = "UPDATE test SET password = '$password' WHERE name = '$user'"; if(mysql_query($query)){ echo "updated";} else{ echo "fail";} ?>





Mohammed said,
Good! that gives me more light on updating information in a
database
Add A Comment