Part-6: Update Record using prepared statement in PDO
I part six, we do the update operation. To do the update we need to select a record which user want to update. From search or display operation that we discuss in previous part user click on edit link and select record for edit. When user select or click on edit link it will pass the id field in GET request to our edit.php file. With the help of record id we retrieve the entire record from table and fill it in to a HTML form where user can do the update operation. After updating information in HTML form user submit the update value by Update button. It pass all the information to our update.php file where the actual update SQL query execute on MySQL table and update the record using prepared statement of PDO.
edit.php
<!DOCTYPE html>
<html>
<body>
<form method="GET" action="update.php">
<?php
require "conn.php";
try
{
$id=$_GET["id"];
$stmt = $conn->prepare("SELECT id, name, email, phone FROM tbl where id=?");
$stmt->execute(array($id));
# setting the fetch mode
echo "<table border='0' align='center' cellpadding='5px' cellspacing='2px'>";
while($row = $stmt->fetch())
{
echo "<tr>";
echo "<td>";
$val=$row['id'];
echo "<input type='hidden' name='txtId' required value=$val>";
echo "</td>";
echo "</tr>";
echo "<tr>";
echo "<td>";
$val=$row['name'];
echo "Name : <input type='text' name='txtName' required value=$val>";
echo "</td>";
echo "</tr>";
echo "<tr>";
echo "<td>";
$val=$row['email'];
echo "Email :<input type='email' name='txtEmail' required value=$val>";
echo "</td>";
echo "</tr>";
echo "<tr>";
echo "<td>";
$val=$row['phone'];
echo "Phone :<input type='number' name='txtPhone' required value=$val>";
echo "</td>";
echo "</tr>";
echo "<tr>";
echo "<td>";
echo "<input type='submit' value='Update'> <input type='reset' value='Clear'> ";
echo "</td>";
echo "</tr>";
}
echo "</table>";
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;
echo "</table>";
?>
</form>
</body>
</html>
update.php
<?php
require("conn.php");
try
{
$stmt = $conn->prepare("update tbl SET name=?, email=?, phone=? where id=?");
$a=$stmt->execute(
array($_GET["txtName"],
$_GET["txtEmail"],
$_GET["txtPhone"],
$_GET["txtId"]));
if($a==true)
{
echo "<br> Record update" ;
}
else
{
echo "<br> Problem in update" ;
}
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
This example is divided in multiple part.
Part-1: Configure and Setup the MySQL database connection using PDO.
Part-2: Create a MySQL Database and a table using PDO.
Part-3: Insert record using prepared statement in PDO.
Part-4: Display Records using prepared statement.
Part-5: Search records using AJAX and PDO in PHP.
Part-6: Update Record using prepared statement in PDO.
Part-7: Delete Record using prepared statement in PDO.
Thanks for providing this informative information…..
ReplyDeleteYou may also refer-