Mysql Insert Data in PHP
To insert data into a MySQL database using MySQLi in PHP, you need to follow these steps:
Connect to the database.
Write an SQL
INSERTquery to add the data.Execute the query using MySQLi.
Check if the insert operation was successful.
Optionally, you can retrieve the last inserted ID if your table has an auto-increment field.
Here's how you can do it in both procedural and object-oriented approaches.
1. Insert Data Using MySQLi (Procedural Approach)
<?php// Database connection parameters$host = "localhost";$username = "root";$password = "";$dbname = "testDB"; // Database where the table is located// Create connection$conn = mysqli_connect($host, $username, $password, $dbname);// Check connectionif (!$conn) { die("Connection failed: " . mysqli_connect_error());}// SQL query to insert a new record$sql = "INSERT INTO users (name, email) VALUES ('John Doe', 'john@example.com')";// Execute the queryif (mysqli_query($conn, $sql)) { echo "New record created successfully."; // Get the last inserted ID $last_id = mysqli_insert_id($conn); echo " Last inserted ID is: " . $last_id;} else { echo "Error: " . $sql . "<br>" . mysqli_error($conn);}// Close the connectionmysqli_close($conn);?>2. Insert Data Using MySQLi (Object-Oriented Approach)
<?php// Database connection parameters$host = "localhost";$username = "root";$password = "";$dbname = "testDB"; // Database where the table is located// Create connection$conn = new mysqli($host, $username, $password, $dbname);// Check connectionif ($conn->connect_error) { die("Connection failed: " . $conn->connect_error);}// SQL query to insert a new record$sql = "INSERT INTO users (name, email) VALUES ('John Doe', 'john@example.com')";// Execute the queryif ($conn->query($sql) === TRUE) { echo "New record created successfully."; // Get the last inserted ID $last_id = $conn->insert_id; echo " Last inserted ID is: " . $last_id;} else { echo "Error: " . $sql . "<br>" . $conn->error;}// Close the connection$conn->close();?>Explanation:
Database Connection:
Procedural: We use
mysqli_connect()to establish a connection to the database.Object-Oriented: We use
new mysqli()to create a connection object to the database.We check if the connection was successful using
ifstatements. If the connection fails, an error message is displayed.
Insert Query:
In the query, we are inserting a new record into the
userstable with thenameandemailfields. You can replace'John Doe'and'john@example.com'with dynamic data (e.g., from a form submission).
Execute the Query:
Procedural: We use
mysqli_query()to execute the SQL query.Object-Oriented: We use
$conn->query()to run the query.
Last Inserted ID:
After inserting the data, we use
mysqli_insert_id($conn)(procedural) or$conn->insert_id(object-oriented) to get the last inserted ID if the table has an auto-increment field (usually the primary key).
Close the Connection:
We close the connection using
mysqli_close()(procedural) or$conn->close()(object-oriented).
Important Notes:
Security: Always use prepared statements to prevent SQL injection attacks. Below is an example of using prepared statements for inserting data securely.
3. Using Prepared Statements (Safe Way to Insert Data)
Procedural Approach (Using Prepared Statements)
<?php// Database connection parameters$host = "localhost";$username = "root";$password = "";$dbname = "testDB"; // Database where the table is located// Create connection$conn = mysqli_connect($host, $username, $password, $dbname);// Check connectionif (!$conn) { die("Connection failed: " . mysqli_connect_error());}// Prepare the SQL query with placeholders$sql = "INSERT INTO users (name, email) VALUES (?, ?)";$stmt = mysqli_prepare($conn, $sql);// Bind parameters to the prepared statement$name = 'John Doe';$email = 'john@example.com';mysqli_stmt_bind_param($stmt, "ss", $name, $email);// Execute the prepared statementif (mysqli_stmt_execute($stmt)) { echo "New record created successfully."; $last_id = mysqli_insert_id($conn); echo " Last inserted ID is: " . $last_id;} else { echo "Error: " . mysqli_error($conn);}// Close the statement and connectionmysqli_stmt_close($stmt);mysqli_close($conn);?>Object-Oriented Approach (Using Prepared Statements)
<?php// Database connection parameters$host = "localhost";$username = "root";$password = "";$dbname = "testDB"; // Database where the table is located// Create connection$conn = new mysqli($host, $username, $password, $dbname);// Check connectionif ($conn->connect_error) { die("Connection failed: " . $conn->connect_error);}// Prepare the SQL query with placeholders$sql = "INSERT INTO users (name, email) VALUES (?, ?)";$stmt = $conn->prepare($sql);// Bind parameters to the prepared statement$name = 'John Doe';$email = 'john@example.com';$stmt->bind_param("ss", $name, $email);// Execute the prepared statementif ($stmt->execute()) { echo "New record created successfully."; $last_id = $conn->insert_id; echo " Last inserted ID is: " . $last_id;} else { echo "Error: " . $conn->error;}// Close the statement and connection$stmt->close();$conn->close();?>This approach ensures the input data is properly escaped and prevents SQL injection.
Let me know if you need further clarifications!