PHP MySQL Insert Data

PHP MySQL Insert Data – Complete Beginner Tutorial

Inserting data into a MySQL database using PHP is one of the most important skills for any web developer. Whether you are building a registration system, contact form, login module, or CMS, inserting data securely and correctly is essential.

This tutorial explains how to insert data into MySQL using PHP, starting from basic concepts to secure methods using prepared statements, with clear examples and output.


What Does Insert Data into MySQL Mean in PHP?

Inserting data means saving user or application data into a MySQL table using PHP code.

PHP communicates with MySQL using database extensions such as:

  • MySQLi (Recommended)
  • PDO (Advanced)

In this tutorial, we use MySQLi because it is simple and beginner-friendly.


Requirements Before Inserting Data Using PHP MySQL

Before inserting data, you need:

  • PHP installed
  • MySQL database
  • A database connection file
  • A table with proper columns

Sample MySQL Table for PHP Insert Example

CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100),
    email VARCHAR(100),
    age INT
);

This table will store user information.


How to Connect PHP with MySQL Database

<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "testdb";

$conn = mysqli_connect($servername, $username, $password, $database);

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

This connection will be used in all insert examples.


Simple PHP MySQL Insert Data Query Example

<?php
$sql = "INSERT INTO users (name, email, age)
        VALUES ('Rahul', 'rahul@example.com', 25)";

if (mysqli_query($conn, $sql)) {
    echo "Data inserted successfully";
} else {
    echo "Error: " . mysqli_error($conn);
}
?>

Output:

Data inserted successfully

Insert Data into MySQL Using PHP Variables

<?php
$name = "Amit";
$email = "amit@gmail.com";
$age = 30;

$sql = "INSERT INTO users (name, email, age)
        VALUES ('$name', '$email', $age)";

if (mysqli_query($conn, $sql)) {
    echo "Record added successfully";
}
?>

Output:

Record added successfully

Insert Form Data into MySQL Using PHP (Most Common Use Case)

HTML Form

<form method="post">
    Name: <input type="text" name="name"><br>
    Email: <input type="email" name="email"><br>
    Age: <input type="number" name="age"><br>
    <input type="submit" name="submit">
</form>

PHP Insert Script

<?php
if (isset($_POST['submit'])) {
    $name = $_POST['name'];
    $email = $_POST['email'];
    $age = $_POST['age'];

    $sql = "INSERT INTO users (name, email, age)
            VALUES ('$name', '$email', $age)";

    if (mysqli_query($conn, $sql)) {
        echo "Form data inserted successfully";
    }
}
?>

Output:

Form data inserted successfully

Secure PHP MySQL Insert Using Prepared Statements

Prepared statements protect your application from SQL Injection.

<?php
$stmt = mysqli_prepare($conn, 
        "INSERT INTO users (name, email, age) VALUES (?, ?, ?)");

mysqli_stmt_bind_param($stmt, "ssi", $name, $email, $age);

$name = "Neha";
$email = "neha@gmail.com";
$age = 22;

mysqli_stmt_execute($stmt);

echo "Data inserted securely";
?>

Output:

Data inserted securely

Why Prepared Statements Are Important in PHP MySQL

Prepared statements:

  • Prevent SQL injection attacks
  • Improve security
  • Increase performance
  • Are recommended for real-world applications

Always use prepared statements when handling user input.


Common Errors While Inserting Data in PHP MySQL

  • Database connection failure
  • Wrong table or column name
  • Missing quotes around strings
  • SQL syntax errors
  • Not validating user input

Always use error handling to debug issues.


Best Practices for PHP MySQL Insert Operations

  • Always validate user input
  • Use prepared statements
  • Avoid storing plain passwords
  • Handle database errors properly
  • Keep database logic separate
  • Close database connection after use

Related Topic

(Add correct internal URLs based on your site structure)


Frequently Asked Questions (FAQ)

1. Which method is best to insert data in PHP MySQL?

Prepared statements using MySQLi or PDO are best.

2. Can I insert multiple rows in one query?

Yes, using a single INSERT query with multiple values.

3. Is MySQLi better than MySQL?

Yes. The old MySQL extension is deprecated.

4. Can PHP insert data without form?

Yes. PHP can insert static or dynamic data.

5. How do I check if data is inserted successfully?

Use mysqli_query() return value or affected rows.

Related Article
50+ PHP Interview Questions and Answers 2023

1. Differentiate between static and dynamic websites. Static Website The content cannot be modified after the script is executed The Read more

All We Need to Know About PHP Ecommerce Development

  Many e-commerce sites let you search for products, show them off, and sell them online. The flood of money Read more

PHP Custom Web Development: How It Can Be Used, What Its Pros and Cons Are,

PHP is a scripting language that runs on the server. It uses server resources to process outputs. It is a Read more

PHP Tutorial

PHP Tutorial – Complete Guide for Beginners to Advanced Welcome to the most comprehensive PHP tutorial available online at PHPOnline.in Read more

Introduction of PHP

Introduction to PHP – Learn PHP from Scratch with Practical Examples Welcome to your complete beginner's guide to PHP. Whether Read more

Syntax Overview of PHP

Syntax Overview of PHP (2025 Edition) Welcome to phponline.in, your one-stop platform for mastering PHP. This comprehensive, SEO-rich tutorial on Read more

Environment Setup in PHP

Setting Up PHP Environment (Beginner’s Guide) If you’re planning to learn PHP or start developing websites using PHP, the first Read more

Variable Types in PHP

PHP Variable Types: Complete Beginner's Guide to PHP Data Types Welcome to phponline.in, your trusted source for beginner-to-advanced level PHP Read more