How can the error of "Undefined variable: mysqli" and "Call to a member function query() on null" be resolved in the edit.php file in PHP?
The error "Undefined variable: mysqli" occurs when the mysqli object is not properly initialized in the edit.php file. To resolve this, make sure to include the database connection code at the beginning of the file to create the mysqli object. The error "Call to a member function query() on null" indicates that the mysqli object is not properly instantiated or there is an issue with the database connection. To fix this, ensure that the mysqli object is successfully created and connected to the database before executing any queries.
<?php
include 'db_connection.php'; // Include the file containing the database connection code
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$id = $_POST['id'];
$name = $_POST['name'];
$description = $_POST['description'];
// Check if mysqli object is properly initialized
if ($mysqli) {
$query = "UPDATE products SET name='$name', description='$description' WHERE id=$id";
$result = $mysqli->query($query);
if ($result) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $mysqli->error;
}
} else {
echo "Database connection error";
}
}
?>
Related Questions
- How can PHP developers effectively validate and handle different types of errors that may occur when making external API requests?
- Why is it important to set the Content-Type header before other headers in a cURL request in PHP?
- What are some common pitfalls to avoid when manipulating database records with PHP based on user interactions?