gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-29 00:05:50 24 4
gpt4 key购买 nike

当你在 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');
}

最佳答案

我更喜欢 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 复制和粘贴到此 block 或从中粘贴 SQL,而无需转义或格式化它。如果您需要包括解析,例如您将使用双引号字符串中的变量,您可以使用 Heredoc。 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');
}

关于php - 如何使 SQL 查询在 PHP 中更具可读性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12783282/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com