Mohamed Karam Mohamed Karam - 6 months ago 27
MySQL Question

Compaing a method with True

I have a question about this code.

$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', '')";

if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;

As far as a I know
$conn -> qurey()
call a method
attached to the object
. How can we compare a method with


From query command documentation:

Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE.

In other words it will return TRUE if insert was successful and FALSE otherwise. So we are comparing function return value after its execution with TRUE to see if it has successfully executed.

You can rewrite this as:

$query_sucessfully_executed = $conn->query($sql);

if ($query_sucessfully_executed) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;

It has the same meaning. I hope this clears things up a bit.

You can learn more about this in query documentation.