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?.
Advertisement
Answer
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?