What is the correct syntax to insert new data into a MySQL database using PHP?
To insert new data into a MySQL database using PHP, you need to establish a connection to the database, construct an SQL query with the data you want to insert, and then execute the query using PHP's mysqli_query() function. Make sure to properly sanitize and validate the data before inserting it into the database to prevent SQL injection attacks.
<?php
// Establish a connection to the database
$connection = mysqli_connect("localhost", "username", "password", "database_name");
// Check connection
if (!$connection) {
die("Connection failed: " . mysqli_connect_error());
}
// Construct SQL query to insert data
$sql = "INSERT INTO table_name (column1, column2, column3) VALUES ('value1', 'value2', 'value3')";
// Execute the query
if (mysqli_query($connection, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($connection);
}
// Close the connection
mysqli_close($connection);
?>