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.
The insert method prepares an SQL statement, binds user input securely, executes the query, and returns the inserted record ID if successful.
// 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 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();
If the insert operation succeeds, the script prints the unique ID of the newly created record. Otherwise, it displays a failure message.