問題描述
有沒有辦法構建類似於 DOMDocument 構建 HTML 文檔的 SQL 查詢? (Is there a way to build SQL queries similar to how DOMDocument builds HTML document?)
有沒有辦法為 HTML 頁面構建類似於 DOMDocument
的 SQL 查詢?
這裡出現語法錯誤的可能性太多:
$query = "SELECT " . $fields . " FROM " . $table;
if ($condition)
$query .= "WHERE status > 1";
是否有第三方或庫存方式來構建類似於 DOMDocument
的查詢?
參考解法
方法 1:
When using plain sql queries I usually don't use multi‑line concats as they lead to a syntax error as you have above. When adding multiple lines for one part, I place the connector (comma for field lists, join for from, and/or for where) at the beginning of the new line.
$query = "SELECT ".$fields;
$query .= " FROM ".$table;
if ($condition) {
$query .= "WHERE status > 1";
}
For some parts using arrays with join() comes in handy:
$conditions = array();
$conditions[] = "status > 1";
// Later on
if ($conditions) {
// Depending on your intention, you can use AND or OR here:
$query .= "WHERE ".join(' AND ', $conditions);
}
But there are many libraries to build queries in an object oriented manner. Last I tested is doctrine's query builder.
(by Roman Toasov、clemens321)