Good day. I decided to talk about how I make out SQL queries in PHP. So, what criteria should my query satisfy: 1. Readability 2. Ability to comment on each action in the request 3. The ability to exclude one of the tables or actions using a comment without removing anything from the query.
Here is an example of a SELECT query: $sql = "SELECT m.id, m.text" .", u.name, u.email" ." FROM messages m" ." LEFT JOIN users u ON u.id=m.user_id" ." WHERE m.status=0" ." AND u.id='".$user_id."'" ." ORDER BY m.date" ." LIMIT 10" ;
So what are the rules of registration, I adhere to: 1. Each operator is on a separate line. 2. Each country is in the "." "", Which makes it possible to comment on how any action $sql = "SELECT m.id, m.text" // ID .", u.name, u.email" // email ." FROM messages m" // ." LEFT JOIN users u ON u.id=m.user_id" ." WHERE m.status=0" // 0 () ." AND u.id='".$user_id."'" // ID ." ORDER BY m.date" // ." LIMIT 10" // 10 ;
so disable one of the query strings $sql = "SELECT m.id, m.text" .", u.name, u.email" ." FROM messages m" ." LEFT JOIN users u ON u.id=m.user_id" ." WHERE m.status=0" ." AND u.id='".$user_id."'" // ." ORDER BY m.date" ." LIMIT 10" ;
3. Any reference to the table is divided into separate lines with grouping by tables, which allows commenting one of the tables to be removed. $sql = "SELECT m.id, m.text" // .", u.name, u.email" ." FROM messages m" // ." LEFT JOIN users u ON u.id=m.user_id" ." WHERE m.status=0" // ." AND u.id='".$user_id."'" ." ORDER BY m.date" ." LIMIT 10" ;
4. After “.", A space is placed before the operators. ." FROM messages m" and in .", u.name, u.email" comma, which makes each line dependent on others. ')
Perhaps this method will seem to someone difficult and not usual, but as practice has shown, having got used to this way of processing requests, the development productivity increases several times.
PS It was not possible to show the issued query with tabs, alas, I did not find how it is done