How can the "INSERT INTO" command be effectively used in PHP to insert data into a MySQL database?
To effectively use the "INSERT INTO" command in PHP to insert data into a MySQL database, you need to establish a database connection, construct an SQL query with the necessary data values, and execute the query using a function like mysqli_query().
<?php
// Establish a connection to the MySQL database
$connection = mysqli_connect("localhost", "username", "password", "database");
// Check connection
if ($connection === false) {
die("Error: Could not connect. " . mysqli_connect_error());
}
// Construct SQL query to insert data into a table
$sql = "INSERT INTO table_name (column1, column2, column3) VALUES ('value1', 'value2', 'value3')";
// Execute the query
if (mysqli_query($connection, $sql)) {
echo "Data inserted successfully.";
} else {
echo "Error: Could not execute $sql. " . mysqli_error($connection);
}
// Close the connection
mysqli_close($connection);
?>
Keywords
Related Questions
- How can the formatting of HTML emails in PHP be optimized to prevent the email content from displaying as source code?
- How can the positioning of functions like header() and session_start() impact the order in which headers are sent in PHP scripts?
- What are some best practices for separating PHP and JavaScript code to avoid errors?