Skip to main content

Practical-19

Write a PHP program for add record into database.

Meta Description

This program shows how to add a record into a database using PHP.

Introdution

Creating a database and adding a record into it is a common programming practice in PHP. This program will help you understand how to add a record into a database using PHP. PHP offers various programming tools like PDO and MySQLi to connect to the database and perform various CRUD operations like creating, updating, and deleting records. So, let's get started! 🚀

Code

<?php

$servername = "localhost";
$username = ""; //Enter the username
$password = ""; //Enter the password
$database = ""; //Enter the databse name

try {
$conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// sql statement for insertion
$sql = "INSERT INTO table_name (column1, column2, etc) VALUES (:value1, :value2, :value3, etc)";
//PDO query
$stmt = $conn->prepare($sql);
// Bind Parameters
$stmt->bindParam(':value1', $value1);
$stmt->bindParam(':value2', $value2);
$stmt->bindParam(':value3', $value3);
//Insert Values
$value1 = 'jhon';
$value2 = 'Doe';
$value3 = 'jhon@example.com';

$stmt->execute();
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}

$conn = null;
?>

Output

New record created successfully.

Explanation

This program connects to the database using PDO and MySQLi. The aim is to add a record into the database using an INSERT statement. The program uses "bindParam()" to bind parameters to a SQL statement, and then execute() the query. Finally, it checks if the record has been created successfully.

Get Help