Skip to content
PHP Logo

How can PHP developers optimize their code to prevent notices and warnings in mysqli queries?

To prevent notices and warnings in mysqli queries, PHP developers can use error suppression techniques such as the "@" symbol to suppress errors, check for errors using mysqli_error() function, and enable error reporting in php.ini file. Additionally, developers can use prepared statements to prevent SQL injection attacks and ensure data integrity.

php
// Example of optimizing mysqli query to prevent notices and warnings
$conn = mysqli_connect("localhost", "username", "password", "database");

// Suppress errors using "@" symbol
$result = @mysqli_query($conn, "SELECT * FROM table");

// Check for errors using mysqli_error() function
if(mysqli_error($conn)){
    echo "Error: " . mysqli_error($conn);
}

// Enable error reporting in php.ini file
// error_reporting(E_ALL);

// Use prepared statements to prevent SQL injection
$stmt = mysqli_prepare($conn, "SELECT * FROM table WHERE id = ?");
mysqli_stmt_bind_param($stmt, "i", $id);
$id = 1;
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);

mysqli_close($conn);