Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP MYSQL line wrap long query?

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

like image 503
Joeme Avatar asked Jun 12 '13 23:06

Joeme


3 Answers

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!

like image 99
Joel Hinz Avatar answered Oct 09 '22 15:10

Joel Hinz


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

like image 39
Jessica Avatar answered Oct 09 '22 16:10

Jessica


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'";
like image 25
Cory Baumer Avatar answered Oct 09 '22 16:10

Cory Baumer