PHP MYSQL line wrap long query?
Solution 1
You can use heredoc, but you should have no problem with line breaks in a string. I often have strings span multiple lines. Heredoc would be a good choice for you though. http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc
Solution 2
PHP doesn't care much about what lines things are on - that's what the semicolons are there for. And neither does MySQL, so you could easily do this:
$query = "SELECT ...
FROM ...
WHERE ...";
And that can definitely help readability when it comes to longer queries!
Solution 3
I'm picky about the query layout in php, especially when it comes to long complicated queries. It just makes it so much more readable.
My Preference
Personally I like the way this looks,
$query =
"SELECT ".
" * ".
"FROM ".
" people ".
"where ".
" people.name = 'bob'";
Why I don't like just using breaks in a string
With this method, theres a ton of extra spaces before each line. Maybe I'm just too OCD about this but I prefer my first method.
$query = "SELECT
*
FROM
people
where
people.name = 'bob'";
Related videos on Youtube
Comments
-
Joeme over 1 year
Little bit of a silly question, but I am learning maybe you can teach me something!!
I sometimes have mysqli queries that are 5 or 6 lines long, I first test them using phpmyadmin where I can press enter to "lay them out" neater for me to see when coding. If I copy and paste them into my php file, they won't work because of the line breaks.
I know I can add to a variable, and have it like:
$query = "SELECT bla bla bla bla"; $query .= " FROM table ..."; $query .= " WHERE ...";
But I just wondered if there was a better/easier/nicer way to lay out my code. I use phpstorm and have wrapping on which is okay, but wraps at the edge of the screen where as it would be nicer to wrap at specific points.
Maybe a bit silly, but nice to know if there is a trick !!
Thanks
-
Joeme almost 11 yearsThanks I will give it a go, I used heredoc without realising it before doing print <<<END I will have another look at why my query fails with the line breaks - it must be something else.
-
Joeme almost 11 yearsThanks I will give it a try and see, really enjoying PHP !! Just finding my way from the intital php/mysql tutorials that seem to be everywhere onto something a bit less hello world and a bit more here's how to do it properly. Thanks again both of you!