Insert Data into Database

PHP MySQL Insert Data
  • In php to store a data using insert data into mysql database use to mysqli and pdo.
  • you can insert data after create a database and datatable.
  • INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,...);

MySQLi Object-Oriented

If run program in your local server like XAMPP, WAMPP, etc. so your server credentials like...

$servername= "localhost";
$username = "root";
$password= ""; (blank)

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "student";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO student_data (first_name, second_name, email, DOB) VALUES ('ram', 'sharma', 'ram@gmail.com', '1999-07-02')";

if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "
" . $conn->error;
}

$conn->close();
?>

MySQLi Procedural

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "student";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

$sql = "INSERT INTO student_data (first_name, second_name, email, DOB) VALUES ('ram', 'sharma', 'ram@gmail.com', '1999-07-02')";

if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "
" . mysqli_error($conn);
}

mysqli_close($conn);
?>

PDO

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "student";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$sql = "INSERT INTO student_data (first_name, second_name, email, DOB) VALUES ('ram', 'sharma', 'ram@gmail.com', '1999-07-02')";

// use exec() because no results are returned
$conn->exec($sql);
echo "New record created successfully";
} catch(PDOException $e) {
echo $sql . "
" . $e->getMessage();
}

$conn = null;
?>