Inserting data into a MySQL database is a fundamental operation in PHP web development. It allows you to add new records to your database tables, which is essential for creating dynamic web applications.
To insert data into a MySQL database using PHP, you'll typically use an SQL INSERT statement within your PHP code. Here's the basic structure:
$sql = "INSERT INTO table_name (column1, column2, column3) VALUES (value1, value2, value3)";
After preparing your SQL statement, you need to execute it using a MySQL connection. Here's a simple example:
connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO users (username, email) VALUES ('JohnDoe', 'john@example.com')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "" . $conn->error;
}
$conn->close();
?>
For better security and to prevent SQL injection, it's recommended to use prepared statements. Here's how you can modify the previous example:
prepare("INSERT INTO users (username, email) VALUES (?, ?)");
$stmt->bind_param("ss", $username, $email);
$username = "JaneDoe";
$email = "jane@example.com";
if ($stmt->execute()) {
echo "New record created successfully";
} else {
echo "Error: " . $stmt->error;
}
$stmt->close();
$conn->close();
?>
To fully understand and implement database operations in PHP, you might want to explore these related topics:
By mastering these concepts, you'll be well-equipped to handle various database operations in your PHP applications.