How can the mysqli.error function be used to troubleshoot issues in PHP code?
When troubleshooting PHP code, the mysqli.error function can be used to retrieve the error message generated by the most recent MySQLi function call. This can help identify issues such as database connection problems, SQL syntax errors, or query execution failures. By checking the error message returned by mysqli.error, developers can pinpoint the root cause of the problem and make the necessary adjustments to their code.
<?php
// Connect to the database
$mysqli = new mysqli("localhost", "username", "password", "database");
// Check for connection errors
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Perform a query
$query = "SELECT * FROM users";
$result = $mysqli->query($query);
// Check for query execution errors
if (!$result) {
die("Query failed: " . $mysqli->error);
}
// Process the query result
while ($row = $result->fetch_assoc()) {
// Do something with the data
}
// Close the database connection
$mysqli->close();
?>
Related questions
-
SQL injection security vulnerabilities PHP script
-
SQL injection user input validation password hashing
-
PDO database operations PHP