PDO Connectivity Step 4

PDO Connectivity Step 4

4. Update Data

<?php
// include database connection file
include_once 'dbconfig.php';

$database = new Connection();
$db = $database->openConnection();

if (isset($_POST['upd'])) {
// Get the userid
    $userid = intval($_GET['update']);

// Posted Values
    $name = $_POST['name'];
    $city = $_POST['city'];

// Query for Updation
    $sql = "update pdo_practice set name=:name,city=:city where id=:id";

//Prepare Query for Execution
    $query = $db->prepare($sql);

// Bind the parameters
    $query->bindParam(':name', $name, PDO::PARAM_STR);
    $query->bindParam(':city', $city, PDO::PARAM_STR);
    $query->bindParam(':id', $userid, PDO::PARAM_STR);

// Query Execution
    $query->execute();

// Mesage after updation
    echo "<script>alert('Record Updated successfully');</script>";

// Code for redirection
    echo "<script>window.location.href='index.php'</script>";
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <head>
		<meta charset="utf-8">
		<title>PHP CRUD Operations using PDO </title>
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
	</head>
</head>
<body>
	<div class="container">
		<div class="row">
			<div class="col-md-9 mx-auto mt-5">
				<h3>Update Record | PHP CRUD Operations using PDO Extension</h3>
				<hr />
<?php
// Get the userid
$userid = intval($_GET['update']);
$sql = "SELECT * from pdo_practice where id=:id";
//Prepare the query:
$query = $db->prepare($sql);
//Bind the parameters
$query->bindParam(':id', $userid, PDO::PARAM_STR);
//Execute the query:
$query->execute();
//Assign the data which you pulled from the database (in the preceding step) to a variable.
$results = $query->fetchAll(PDO::FETCH_OBJ);
// For serial number initialization
$cnt = 1;
if ($query->rowCount() > 0) {
//In case that the query returned at least one record, we can echo the records within a foreach loop:
    foreach ($results as $result) {
        ?>
<form name="insertrecord" method="post">
	<label>Name</label>
		<input type="text" name="name" value="<?php echo htmlentities($result->name); ?>" class="form-control" required>
	<label class="mt-3">City</label>
		<select name="city" class="form-select" required>
			<option disabled>Select City</option>
			<option value="Ludhiana">Ludhiana</option>
			<option value="Chandigarh">Chandigarh</option>
			<option value="Delhi">Delhi</option>
		</select>
<?php }}?>
		<input type="submit" class="btn btn-primary mt-3" name="upd" value="Submit">
				</form>
			</div>
		</div>
	</div>
</body>
</html>

Post Your Comments & Reviews

Your email address will not be published. Required fields are marked *

*

*