How to Insert data using bindParam function in php pdo
How to Insert data using bindParam function in php pdo
In this tutorial, you will be learning about how to insert data using "bindParam()" function in php pdo.
We are using bootstrap v5 to design the user Interface.
Step 1: Create a Database Connection.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$database = "database_name";
try {
$conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // set the PDO error mode to exception
// echo "Connected Successfully";
} catch(PDOException $e) {
echo "Connection Failed" .$e->getMessage();
}
?>
Step 2: Create a file named student-add.php and paste below form:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
<title>PHP PDO using bindParam() function CRUD</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-12 mt-4">
<div class="card">
<div class="card-header">
<h4> Add Data using PDO with bindParam() in PHP
<a href="index.php" class="btn btn-primary float-end">BACK</a>
</h4>
</div>
<div class="card-body">
<form action="code.php" method="POST">
<div class="mb-3">
<label>Full Name</label>
<input type="text" name="fullname" class="form-control">
</div>
<div class="mb-3">
<label>Email Id</label>
<input type="email" name="email" class="form-control">
</div>
<div class="mb-3">
<label>Phone Number</label>
<input type="text" name="phone" class="form-control">
</div>
<div class="mb-3">
<label>Course</label>
<input type="text" name="course" class="form-control">
</div>
<div class="mb-3">
<button type="submit" name="save_student" class="btn btn-primary">Save Student</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
After form submit, it takes the action to code.php with post method.
Step 3: Create a code.php file and paste the below code:
<?php
session_start();
include('dbcon.php');
if(isset($_POST['save_student']))
{
$fullname = $_POST['fullname'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$course = $_POST['course'];
try {
$query = "INSERT INTO students (fullname, email, phone, course) VALUES (?, ?, ?, ?)";
$statement = $conn->prepare($query);
$statement->bindParam(1, $fullname);
$statement->bindParam(2, $email);
$statement->bindParam(3, $phone);
$statement->bindParam(4, $course);
$query_execute = $statement->execute();
if($query_execute)
{
$_SESSION['message'] = "Added Successfully";
header('Location: index.php');
exit(0);
}
else
{
$_SESSION['message'] = "Not Added";
header('Location: index.php');
exit(0);
}
} catch (PDOException $e) {
echo "My Error Type:". $e->getMessage();
}
}
?>
Thank you.