← Back to Chapters

PHP CRUD Class – Insert Method

? PHP CRUD Class – Insert Method

? Quick Overview

The Insert method in a PHP CRUD class allows you to add new records to a database table efficiently using prepared statements. This approach improves security, readability, and maintainability.

? Key Concepts

  • Object-Oriented PHP CRUD structure
  • Prepared statements for secure inserts
  • Returning inserted record ID

? Syntax & Theory

The insert method prepares an SQL statement, binds user input securely, executes the query, and returns the inserted record ID if successful.

? CRUD Class with Insert Method

? View Code Example
// PHP CRUD class with insert method
class User {
private $conn;
private $table = "users";

public function __construct($db) {
$this->conn = $db;
}

public function insert($first_name, $last_name, $email) {
$stmt = $this->conn->prepare("INSERT INTO " . $this->table . " (first_name, last_name, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $first_name, $last_name, $email);
if ($stmt->execute()) {
return $this->conn->insert_id;
} else {
return false;
}
}
}

? Using the Insert Method

? View Code Example
// Using the insert method to add a new user
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed");
}

$user = new User($conn);
$inserted_id = $user->insert("John", "Doe", "john.doe@example.com");

if ($inserted_id) {
echo "User inserted successfully with ID: " . $inserted_id;
} else {
echo "Insertion failed.";
}

$conn->close();

? Live Output / Explanation

If the insert operation succeeds, the script prints the unique ID of the newly created record. Otherwise, it displays a failure message.

? Use Cases

  • User registration systems
  • Admin panels for data entry
  • Storing form submissions securely

✅ Tips & Best Practices

  • Always validate and sanitize user input
  • Use transactions when inserting related records
  • Reuse CRUD classes for consistency

? Try It Yourself

  • Add more fields like phone or address
  • Connect the insert method to an HTML form
  • Log insert errors for debugging