query function takes a valid SQL string and executes it directly against the database connection
Object oriented style
$result = $conn->query("SELECT * FROM `people`");
$result = mysqli_query($conn, "SELECT * FROM `people`");
A common problem here is that people will simply execute the query and expect it to work (i.e. return a mysqli_stmt object). Since this function takes only a string, you're building the query first yourself. If there are any mistakes in the SQL at all, the MySQL compiler will fail, at which point this function will return
$result = $conn->query('SELECT * FROM non_existent_table'); // This query will fail $row = $result->fetch_assoc();
The above code will generate a
E_FATAL error because
false, and not an object.
PHP Fatal error: Call to a member function fetch_assoc() on a non-object
The procedural error is similar, but not fatal, because we're just violating the expectations of the function.
$row = mysqli_fetch_assoc($result); // same query as previous
You will get the following message from PHP
mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given
You can avoid this by doing a test first
if($result) $row = mysqli_fetch_assoc($result);