在典型的 PHP SQL 准备语句中,字段名称被多次提及,导致冗余。要解决此问题,请考虑以下解决方案:
$data = [$taskName, $startDate, $completedDate]; $sql = 'INSERT INTO tasks VALUES(null, ?, ?, ?)'; $db->prepare($sql)->execute($data);
为接受表名和数据数组的插入创建辅助函数,处理 SQL 注入问题:
function escape_mysql_identifier($field){ return "`".str_replace("`", "``", $field)."`"; } function prepared_insert($conn, $table, $data) { $keys = array_keys($data); $keys = array_map('escape_mysql_identifier', $keys); $fields = implode(",", $keys); $table = escape_mysql_identifier($table); $placeholders = str_repeat('?,', count($keys) - 1) . '?'; $sql = "INSERT INTO $table ($fields) VALUES ($placeholders)"; $conn->prepare($sql)->execute(array_values($data)); }
prepared_insert($db, 'tasks',[ 'task_name' => $taskName, 'start_date' => $startDate, 'completed_date' => $completedDate, ]);
使用对象实现一个小型 ORM面向编程,定义通用方法的原型类,并根据表名和列列表为表创建特定的类。
public function create($data): int { $fields = $this->makeFieldList($data); $placeholders = str_repeat('?,', count($data) - 1) . '?'; $sql = "INSERT INTO `$this->table` ($fields) VALUES ($placeholders)"; $this->sql($sql,array_values($data)); return $this->db->lastInsertId(); } class UserGateway extends BasicTableGateway { protected $table = 'gw_users'; protected $fields = ['email', 'password', 'name', 'birthday']; }
$data = [ 'email' => '[email protected]', 'password' => 123, 'name' => 'Fooster', ]; $userGateway = new UserGateway($pdo); $id = $userGateway->create($data); echo "Create: $id", PHP_EOL;
以上是如何减少 PHP SQL 准备语句中的代码重复?的详细内容。更多信息请关注PHP中文网其他相关文章!