PDO Connectivity Step 2
2. Insert Data
<?php
// include database connection file
include_once 'dbconfig.php';
$database = new Connection();
$db = $database->openConnection();
if (isset($_POST['insert'])) {
// Posted Values
$name = $_POST['name'];
$city = $_POST['city'];
// Query for Insertion
$sql = "INSERT INTO pdo_practice(name,city) VALUES(:name,:city)";
//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 Execution
$query->execute();
// Check that the insertion really worked. If the last inserted id is greater than zero, the insertion worked.
$lastInsertId = $db->lastInsertId();
if ($lastInsertId) {
// Message for successfull insertion
echo "<script>alert('Record inserted successfully');</script>";
echo "<script>window.location.href='index.php'</script>";
} else {
// Message for unsuccessfull insertion
echo "<script>alert('Something went wrong. Please try again');</script>";
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>
<body>
<div class="container">
<div class="row">
<div class="col-md-9 mx-auto mt-5">
<h3>Insert Record | PHP CRUD Operations using PDO Extension</h3>
<hr />
<form name="insertrecord" method="post">
<label>Name</label>
<input type="text" name="name" class="form-control" required>
<label class="mt-3">City</label>
<select name="city" class="form-select" required>
<option value="" disabled="disabled">Select City</option>
<option value="Ludhiana">Ludhiana</option>
<option value="Chandigarh">Chandigarh</option>
<option value="Delhi">Delhi</option>
</select>
<input type="submit" class="btn btn-primary mt-3" name="insert" value="Submit">
</form>
</div>
</div>
</div>
</body>
</html>