HOW TO UPDATE+FETCH DATA IN PHP - CULT CODE
In this tutorial, we will learn how to UPDATE+FETCH data in PHP using HTML form.
1. Create a table name user.
Use the code below to create a table:
CREATE TABLE `user` (
`id` int(11) NOT NULL,
`username` varchar(251) NOT NULL,
`email` varchar(251) NOT NULL,
`password` varchar(251) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
2. Now create a file connect.php:
This file will help us to connect PHP to Mysql.
<?php
$connect = mysqli_connect("localhost", "root", "password", "demo");
?>
3. Now create a file index.php:
In this file, we will create an HTML form and fetch data using PHP.
<?php
include('connect.php');
include('update.php');
$data_query = "SELECT * FROM user LIMIT 1";
$data_result = mysqli_query($connect, $data_query);
if(mysqli_num_rows($data_result) > 0)
{
while($row = mysqli_fetch_array($data_result))
{
?>
<h3>Update Data</h3>
<form method="POST" action="">
<label>ID</label><br><br>
<input type="text" readonly name="id" value="<?php echo $row['id']; ?>" /><br></br>
<label>Name</label><br><br>
<input type="text" name="username" value="<?php echo $row['username']; ?>" /><br><br>
<label>Email</label><br><br>
<input type="text" name="email" value="<?php echo $row['email']; ?>" /><br><br>
<input type="submit" name="update" value="Update"></input><br><br>
</form>
<?php
}
}
?>
4. Now create a file update.php:
This file will help us to UPDATE existing data in MySQL using PHP.
<?php
if(isset($_POST["update"]))
{
include('connect.php');
$username = mysqli_real_escape_string($connect, $_POST["username"]);
$email = mysqli_real_escape_string($connect, $_POST["email"]);
$id = mysqli_real_escape_string($connect, $_POST["id"]);
$sql = "UPDATE user SET username='$username', email='$email' WHERE id='$id'";
if(mysqli_query($connect, $sql)){
echo '<script>alert("Data Updated!");</script>';
}else{
echo '<script>alert("Something Went wrong!");</script>';
}
}
?>
5. Run your Project:
Step 1 :
Step 2:
Make changes and click on Update.
Step 3:
Compare:





Comments
Post a Comment