Isn't needed calling the mysqli function to insert values?

Viewed 128

I am learning MySQL and PHP, I have seen that with this code you can insert values in the database:

$sql = "INSERT QUERY..."
$insert = mysqli_query($connection, $sql);

if($insert){
 echo "Insert Worked";
}else{
 echo "Insert error". mysqli_error($connection);
}

So like you see, this should work, but I don't get how. If you are never calling the function mysqli_query, it is just stored in the $insert variable. It's called in the if condition?

Another thing that called my attention is that you get the error of that insert in the connection query, is not that a bad thing? I mean, if you have a lot of errors in different queries it's not too useful, is this the way for looking for errors?.

3 Answers

In most languages, including PHP, anything that follows = (assignment operator) is evaluated before it is stored in a given variable. Whatever follows the assignment operator = until the ; is parsed as an expression and that expression may include function calls. Those function calls are evaluated right away and the result of those function calls is used in the rest of the evaluation of the expression.

In your case, mysqli_query() function is called and the rows are inserted then the value returned by mysqli_query() is stored in the variable $insert. It's not called when evaluating the if statement.

About your error handling question, like @O.Jones said, each connection runs 1 query at a time so, if you have multiple queries, you would need to run a query and then check for error and do this in a series.

Also, like @Dharman mentioned, you should use mysqli_error() with care as it is not desirable to use it in production unless you know and have a well-thought use case. Read more about what @Dharman has to say here: Should we ever check for mysqli_connect() errors manually?

You are calling mysqli_query, and storing the result in $insert. Since you're using an insert statement, $insert will contain have TRUE or FALSE, depending on whether the insert statement was successful or not.

Each connection is capable of handling one query at a time; that's the way MySQL and other client-server-style database systems work. The mysqli API designers decided to make errors accessible via the connection object, not the query object. It's a reasonable decision; ordinarily an application program like yours must handle errors before running new queries, so it makes less sense to hold errors on the query object.

An error is signified by the mysqli_query() returned value coming back falsy. If it comes back truthy, you can do more things with it. If you're not sure about "falsy" and "truthy" please look tehm up.

But, these are, at their root, decisions made by API designers doing their best to create useful APIs.

(And, of course, you do use mysqli_query() in your code sample..)

Related