What are some best practices for debugging PHP code that is not inserting data into a database as expected?

Issue: When PHP code is not inserting data into a database as expected, it could be due to errors in the SQL query, connection issues, or incorrect data being passed to the query. To debug this issue, you can start by checking the SQL query for errors, ensuring the database connection is established correctly, and verifying that the data being passed to the query is in the correct format.

// Example PHP code snippet to debug database insertion issue

// Establish database connection
$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);
}

// Sample SQL query to insert data into a table
$sql = "INSERT INTO table_name (column1, column2) VALUES ('$value1', '$value2')";

// Check if the query is executed successfully
if ($conn->query($sql) === TRUE) {
    echo "Record inserted successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

// Close database connection
$conn->close();