MySQLi query

suggest change

The query function takes a valid SQL string and executes it directly against the database connection $conn

Object oriented style

$result = $conn->query("SELECT * FROM `people`");

Procedural style

$result = mysqli_query($conn, "SELECT * FROM `people`");

CAUTION

query returns a mysqli_result for a successful SELECT, true for other successful statements, and false when the SQL fails. A statement object comes from prepare, not from query. The SQL is only a string, so a bad query fails inside MySQL and query returns false.

$result = $conn->query('SELECT * FROM non_existent_table'); // This query will fail
$row = $result->fetch_assoc();

The next line fails because $result is false, not a result object. On current PHP both the object call and the procedural call throw a TypeError if they are not caught. Older PHP reported a fatal error for the object call and a warning for the procedural call.

$row = mysqli_fetch_assoc($result); // same query as previous

You will get the following message from PHP

mysqli_fetch_assoc(): Argument #1 ($result) must be of type mysqli_result, false given

You can avoid this by doing a test first

if($result) $row = mysqli_fetch_assoc($result);

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents