July 25, 2017
update record in php using parameterized query
In this example, we update record in php. The database table whose record are updated has following details
tblstudent (id, name, age, address), where id is an auto-increment primary key
Suppose we want to update record against id = 1
The following is the code. The code of opendb.php is defined here
<html> <head> </head> <body> <?php include("opendb.php"); $msg = ""; $txtname = isset($_POST['txtname'])? $_POST['txtname'] : ""; $txtage = isset($_POST['txtage'])? $_POST['txtage'] : ""; $txtaddress = isset($_POST['txtaddress'])? $_POST['txtaddress'] : ""; if(isset($_POST['btnupdate'])) { $query = "update tblstudent set name=:name, age=:age, address=:address where id=1"; try { $stmt = $conn->prepare( $query ); $stmt->bindParam(':name', $txtname); $stmt->bindParam(':age', $txtage); $stmt->bindParam(':address', $txtaddress); $result = $stmt->execute(); $msg = "Record updated"; } catch(PDOException $ex) { $msg = $ex -> getMessage(); } } $query = "select id, name, age, address from tblstudent where id=1"; $stmt = $conn->prepare( $query ); $result = $stmt->execute(); while($row = $stmt->fetch()) { //echo $row['id'] . " " . $row['name'] . " " . $row['age'] . " " . $row['address']; $txtname = $row['name']; $txtage = $row['age']; $txtaddress = $row['address']; } ?> <form id="frm" name="frm" method="post" action=""> <table border="1"> <tr> <td>Name</td> <td><input id="txtname" name="txtname" type="text" value="<?php echo $txtname; ?>" /></td> </tr> <tr> <td>Age</td> <td><input type="text" name="txtage" id="txtage" value="<?php echo $txtage; ?>"></td> </tr> <tr> <td>Address</td> <td><textarea name="txtaddress" id="txtaddress" cols="45" rows="5"><?php echo $txtaddress; ?></textarea></td> </tr> <tr> <td></td> <td><input type="submit" name="btnupdate" id="btnupdate" value="Update"></td> </tr> <tr> <td></td> <td><?php echo $msg; ?></td> </tr> </table> </form> <?php $conn = NULL; ?> </body> </html>