A shortened version of weblog.

A shortened version of weblog.

PHP MySQL Insert Data

  • Programming
  • 10 June 2022
  • 870 Views
  • Sathiyamoorthy V

1. PHP MySQL Insert Data ( MySQLi Object-Oriented )

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

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// sql to insert data
$sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com')";

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

$conn->close();
?>

2. PHP MySQL Insert Data ( MySQLi Procedural )

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

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// sql to insert data
$sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com')";

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

mysqli_close($conn);
?>

3. PHP MySQL Insert Data ( PDO )

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

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 MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com')";
// use exec() because no results are returned
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}

$conn = null;
?>

RELATED POST

10 June 2022   |   Programming
PHP MySQL Create Table
Read More
10 June 2022   |   Programming
PHP Create a MySQL Database
Read More
09 June 2022   |   Programming
PHP Connect to MySQL
Read More
19 June 2022   |   Programming
PHP MySQL Select Data
Read More
20 September 2022   |   Programming
IoT - Internet of Things Presentations & Programming Materials
Read More
29 May 2023   |   Programming
MySQL vs. MongoDB: What is the Difference?
Read More
PHP MySQL Insert Data
https://blogbyte.in/blog-details/?cid=2&pid=37

LEAVE A COMMENT

+