初學者常因手寫 SQL 字串拼接導致語法錯誤、SQL 注入風險。本類別封裝欄位設定與語句生成,自動處理引號跳脫、數值不加引號、欄位逗號修飾,讓新手專注業務邏輯。
<?php
class SqlBuilder
{
private $table = '';
private $params = []; // ['field' => [value, is_numeric]]
public function __construct(string $table)
{
$this->table = $table;
}
/**
* 設定欄位值
*
* @param string $name 欄位名
* @param mixed $value 值
* @param bool $isNumeric 是否為數值型(true 則不加引號)
* @return $this 支援鏈式呼叫
*/
public function set(string $name, $value, bool $isNumeric = false): self
{
// 單引號跳脫:' -> ''
$value = is_string($value) ? str_replace("'", "''", $value) : $value;
$this->params[$name] = [$value, $isNumeric];
return $this;
}
/** 產生 INSERT 語句 */
public function insertSql(): string
{
if (empty($this->params)) {
throw new LogicException('尚未設定任何欄位');
}
$keys = implode(',', array_keys($this->params));
$values = [];
foreach ($this->params as $val) {
$values[] = $val[1] ? $val[0] : "'{$val[0]}'";
}
return "INSERT INTO {$this->table} ($keys) VALUES (" . implode(',', $values) . ")";
}
/** 產生 UPDATE 語句
* @param string $where WHERE 條件(不含 WHERE 關鍵字),如 "id = 5"
*/
public function updateSql(string $where): string
{
if (empty($this->params)) {
throw new LogicException('尚未設定任何欄位');
}
$sets = [];
foreach ($this->params as $key => $val) {
$sets[] = "$key = " . ($val[1] ? $val[0] : "'{$val[0]}'");
}
return "UPDATE {$this->table} SET " . implode(',', $sets) . " WHERE $where";
}
}
<?php
require 'SqlBuilder.php';
$builder = new SqlBuilder('users');
$builder->set('username', 'john_doe')
->set('email', 'john@example.com')
->set('age', 28, true) // 數值不加引號
->set('status', 1, true);
echo $builder->insertSql();
// INSERT INTO users (username,email,age,status) VALUES ('john_doe','john@example.com',28,1)
echo $builder->updateSql('id = 10');
// UPDATE users SET username = 'john_doe', email = 'john@example.com', age = 28, status = 1 WHERE id = 10
['sql' => '...', 'params' => [...]],配合 PDO::execute() 徹底防注入。where('age', '>', 18) 自動生成條件片段。insertMulti([['name'=>'A'], ['name'=>'B']]) 生成 VALUES (...), (...)。deleteSql(), selectSql()。本類別僅做字串組裝,**不替代參數綁定**。正式專務請改用 PDO 預處理或成熟 ORM(Eloquent, Doctrine, Cycle ORM)。本類適合教學、原型快速驗證、低風險內部工具。