What is the correct syntax for inserting data into a specific row in a MySQL table using PHP?
To insert data into a specific row in a MySQL table using PHP, you need to use an SQL query with a WHERE clause that specifies the row you want to update. The WHERE clause should include a condition that uniquely identifies the row, such as the primary key. Make sure to properly sanitize and validate the data before inserting it into the database to prevent SQL injection attacks.
<?php
// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Define the data to be inserted
$data1 = "value1";
$data2 = "value2";
// SQL query to insert data into a specific row
$sql = "UPDATE table_name SET column1='$data1', column2='$data2' WHERE id=1";
// Execute the query
if ($conn->query($sql) === TRUE) {
echo "Data inserted successfully into the specific row";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
// Close the connection
$conn->close();
?>