5

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

4

3 回答 3

11

PHP 不太关心事情在哪一行——这就是分号的用途。MySQL 也没有,所以你可以很容易地做到这一点:

$query = "SELECT ...
    FROM ...
    WHERE ...";

当涉及到更长的查询时,这绝对有助于提高可读性!

于 2013-06-12T23:24:01.277 回答
2

我对 php 中的查询布局很挑剔,尤其是在涉及长而复杂的查询时。它只是使它更具可读性。

我的偏好

我个人喜欢这个样子,

$query =
  "SELECT ".
  "    * ".
  "FROM ".
  "    people ".
  "where ".
  "    people.name = 'bob'";

为什么我不喜欢在字符串中使用中断

使用这种方法,每行之前都会有大量额外的空格。也许我对此过于强迫症,但我更喜欢我的第一种方法。

$query = "SELECT
      *
  FROM
      people
  where
      people.name = 'bob'";
于 2014-08-27T04:00:26.180 回答
2

您可以使用heredoc,但字符串中的换行符应该没有问题。我经常让字符串跨越多行。不过,Heredoc 对您来说是个不错的选择。http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc

于 2013-06-12T23:25:28.393 回答