Insert Data

Last updated on

pplications. Such As as From registering new users to collecting form submissions and storing product details.

Things like adding a user profile information during sign-up or saving feedback from a contact form—these operations rely heavily on the integration between PHP and MySQL.

In this guide, you will learn many ways to insert data into MySQL using PHP, covering everything from basic SQL syntax to secure examples like prepared statements.

Basic Syntax of the INSERT Data INTO SQL Statement

The INSERT INTO SQL command is used to add new rows of data to a table in a database.

This assumes that you will provide values for all columns in the correct order. Here is the syntax:

INSERT INTO table_name VALUES (value1, value2, value3, ...);

To use another pattern for this statement is to specify columns name with values:

INSERT INTO table_name (column1, column2, column3, ...) VALUES (value1, value2, value3, ...);

These two statements are only to show you how to insert data into SQL, but how can you achieve that in PHP? Actually, we have two ways to do that! MySQLi and PDO. In the following section you will learn each one in details.

Insert Data into MySQL Using PHP

PHP provides two ways to allow you insert data into SQL database which are PDO and MySQLi.

Inserting Data Using mysqli

The mysqli extension to interact with MySQL databases. It provides us two ways to insert data. They are procedural and object-oriented.

Here is the procedural method:

$conn = mysqli_connect("localhost", "username", "password", "database");

if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$sql = "INSERT INTO users (name, email) VALUES ('Jane Doe', 'jane.doe@example.com')";
if (mysqli_query($conn, $sql)) {
    echo "New record created successfully.";
} else {
    echo "Error: " . mysqli_error($conn);
}

mysqli_close($conn);

And here the Object-oriented method:

$conn = new mysqli("localhost", "username", "password", "database");

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

$sql = "INSERT INTO users (name, email) VALUES ('Jane Smith', 'jane.smith@example.com')";
if ($conn->query($sql) === TRUE) {
    echo "Record added successfully.";
} else {
    echo "Error: " . $conn->error;
}

$conn->close();

Both of them handle errors using the respective error functions. Here is another example using prepared statements for secure data insertion.

$conn = mysqli_connect("localhost", "username", "password", "database");
$stmt = $conn->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->bind_param("ss", $name, $email);

$name = "Rachel Green";
$email = "rachel.green@example.com";
$stmt->execute();

echo "Record inserted successfully.";
$stmt->close();
$conn->close();

Anyway, let's move on to the section below to see how to insert data into SQL using PDO in PHP.

Inserting Data to MySQL Using PDO

You need first to set up a connection between SQL and PHP. Here is the code of connection using PHP:

try {
    $pdo = new PDO("mysql:host=localhost;dbname=database", "username", "password");
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}

To execute an insert query use the below one:

$sql = "INSERT INTO users (name, email) VALUES ('Mike Ross', 'mike.ross@example.com')";
try {
    $pdo->exec($sql);
    echo "New record created successfully.";
} catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
}

Here is another example using prepared statements:

$stmt = $pdo->prepare("INSERT INTO users (name, email) VALUES (:name, :email)");
$stmt->execute(['name' => 'Joey Tribbiani', 'email' => 'joey.tribbiani@example.com']);
echo "Record inserted successfully.";

In the following section, you will learn how to insert multiple rows into the database in a single execution.

Insert Multiple Rows of Data into MySQL in PHP

You can insert multiple rows with a single query to improve performance. Just use this example:

$sql = "INSERT INTO users (name, email) VALUES 
('Alice', 'alice@example.com'),
('Bob', 'bob@example.com'),
('Charlie', 'charlie@example.com')";

$conn->query($sql);

Let's summarize it.

Wrapping Up

The process of Insert data to a MySQL database with PHP is one of the basic tasks in web development.

It involves using the INSERT INTO SQL statement to add new rows of data into a database table, a task commonly required for operations like user registrations or storing form submissions. To achieve this, PHP provides two primary extensions: MySQLi and PDO.

MySQLi offers both procedural and object-oriented approaches, while PDO provides a database-agnostic solution. Both methods support prepared statements, which are important for securing data inputs against SQL injection. By establishing a database connection in PHP and executing INSERT INTO queries using these extensions, you can securely manage data insertion in your projects.

Frequently Asked Questions (FAQs)

  • What is the basic syntax for inserting data into a MySQL database using PHP?

    To insert data into a MySQL database, use the INSERT INTO SQL statement. Here’s an example using PHP and mysqli:
    $conn = mysqli_connect("localhost", "username", "password", "database");
    $sql = "INSERT INTO users (name, email) VALUES ('John Doe', 'john@example.com')";
    mysqli_query($conn, $sql);
    mysqli_close($conn);
    
  • How can I insert data securely into MySQL to prevent SQL injection?

    Use prepared statements to securely insert data. Here’s an example with
    mysqli:
    $conn = mysqli_connect("localhost", "username", "password", "database");
    $stmt = $conn->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
    $stmt->bind_param("ss", $name, $email);
    $name = "Jane Doe";
    $email = "jane@example.com";
    $stmt->execute();
    $stmt->close();
    $conn->close();
    
  • How do I insert data from an HTML form into a MySQL database?

    Retrieve form data using $_POST, validate it, and insert it into the database. Example: HTML Form:
    <form action="insert.php" method="POST">
        <input type="text" name="name" placeholder="Name">
        <input type="email" name="email" placeholder="Email">
        <button type="submit">Submit</button>
    </form>
    
    PHP Script:
    $conn = mysqli_connect("localhost", "username", "password", "database");
    $name = $_POST['name'];
    $email = $_POST['email'];
    $stmt = $conn->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
    $stmt->bind_param("ss", $name, $email);
    $stmt->execute();
    $stmt->close();
    $conn->close();
    
  • What are common errors when inserting data into MySQL?

    • Connection errors: Ensure the database credentials are correct.
    • SQL syntax errors: Double-check your query for typos.
    • Data type mismatches: Ensure values match column data types.
    Use
    mysqli_error() or try-catch with PDO for debugging.
  • What is the difference between `mysqli` and `PDO` for inserting data?

    • mysqli: Easier to use for MySQL-specific operations. Example:
    $conn = mysqli_connect("localhost", "username", "password", "database");
        $sql = "INSERT INTO users (name, email) VALUES ('John', 'john@example.com')";
        mysqli_query($conn, $sql);
        mysqli_close($conn);
        
  • PDO: Supports multiple database types and has advanced features. Example:
$pdo = new PDO("mysql:host=localhost;dbname=database", "username", "password");
    $stmt = $pdo->prepare("INSERT INTO users (name, email) VALUES (:name, :email)");
    $stmt->execute(['name' => 'Jane', 'email' => 'jane@example.com']);