Semicolon ends in php / mysqli?

(Not only) because I often copy and paste my queries from one place to another (code, mysql-workbench, command line client, etc.), I used to end my queries with semicolons.

I found the following note in php.net documentation today:

"Note: You must not add a trailing semicolon or \ g to a statement."

http://php.net/manual/en/mysqli.prepare.php

Is there a reason why the semicolon is not only optional, but php.net even forbids its use? Seems a bit odd to me, but I didn't actually find any links to this topic regarding mysqli (which is what is currently being used here at work).

I hope I didn't miss anything when searching. Can someone shed some light on this? I suppose there must be a reason why php.net discourages something that is not necessarily mysql at best.

Many thanks.

+3


source to share


2 answers


Larry Ullman has a good answer for this.

Simply put, it is bad practice to end your query with a semicolon in PHP.



It won't hurt your code anyway, whether you do it or not. But when you work with Oracle or Microsoft SQL or any other database application, these queries may become unusable due to this semicolon. And it would be a pain in the neck to go to each query line and delete it.

Remove that semicolon instead :)

+1


source


I believe the reason is closely related to theirs (PHP.net), discouraging prepared statements making multiple queries as one. I will clarify.

Prepared statements have many advantages, but the important topic here is that they can be cached and run again without reinstalling objects, since the prepared statement had its variables passed as references instead of static values. Because of this, executing a statement associated with specific references makes it more useful as an object in memory than closing it and then reopening and re-creating it.

With that in mind, it actually makes sense to make the individual statements as objects that are instantiated using the wrapper class and then execute them as needed as many times as necessary.



Now we hit the ending semicolon and my faith. Since it is very easy to believe and understand why prepared statements (or any statement that exists as an object) should NOT contain more than one statement, it is just as easy to believe that PHP.net developed mysqli meaning that they did have one of the functions used to prepare / bind / execute an SQL query, add a semicolon FOR . If so, then adding another semicolon in the end is generally harmless in some cases, but introduces errors in others.

So my conclusion is that they will only prevent such a normal element from being included if the methods we call really care about it for us. If so, why did they do it? It is possible to use ready-made statements as separate requests and easily discourage the use of multiple requests in one prepared statement.

-1


source







All Articles