如何使SQL查询在PHP中更具可读性?

2022-08-30 20:48:15

当 SQL 查询中有很长的字段时,如何使其更具可读性?

例如:

public function findSomethingByFieldNameId($Id) {
        $sql = "SELECT field1, field2, field3 as Field3_Something, field4, field5, field6, field7, field8, field9
                      FROM table
               JOIN table2 AS TNS ON TNS.id = table.id
                      WHERE something = 1";
 return $this->db->fetchData($sql, null, 'all');
    }

答案 1

我更喜欢Heredoc语法,尽管Nowdoc也适用于您的示例:

黑血树:

http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc

诺多克: http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.nowdoc

两者的优点是,您可以将直接 SQL 复制并粘贴到此块中,而不必对其进行转义或格式化。如果您需要包含解析,例如使用双引号字符串中的变量,则可以使用Heredoc。Nowdoc 的行为类似于单引号。

Nowdoc:

public function findSomethingByFieldNameId($Id) {
    $sql = <<<'SQL'
    SELECT field1, field2, field3 as Field3_Something, field4, field5, field6, field7, field8, field9
    FROM table
    JOIN table2 AS TNS ON TNS.id = table.id
    WHERE something = 1
SQL;

    return $this->db->fetchData($sql, null, 'all');
}

黑血树:

public function findSomethingByFieldNameId($Id) {
    $sql = <<<SQL
    SELECT field1, field2, field3 as Field3_Something, field4, field5, field6, field7, field8, field9
    FROM table
    JOIN table2 AS TNS ON TNS.id = table.id
    WHERE something = '$Id'
SQL;

    $sql = mysql_real_escape_string($sql);

    return $this->db->fetchData($sql, null, 'all');
}

答案 2

您可以像这样连接它,以使其更具可读性:

$sql = "SELECT field1, field2, field3 as Field3_Something,";
$sql.= " field4, field5, field6, field7, field8, field9";
$sql.= " FROM table JOIN table2 AS TNS ON TNS.id = table.id";
$sql.= " WHERE something = 1";

注意:在连接查询时,请务必在双引号之间开始新行之前留出空格,否则您将收到查询无效错误


推荐