From df92aeac5e5334a2bdf135f5ef4789232f609410 Mon Sep 17 00:00:00 2001 From: se <6008932+se@users.noreply.github.com> Date: Mon, 17 Mar 2025 09:17:49 +0800 Subject: [PATCH] update with where update with where statement --- src/Database.php | 39 +++++++++++++++++++++++++++------------ 1 file changed, 27 insertions(+), 12 deletions(-) diff --git a/src/Database.php b/src/Database.php index bc77c12..337c7c0 100644 --- a/src/Database.php +++ b/src/Database.php @@ -194,13 +194,14 @@ public function insert($table, $data) * * @param string $table table name * @param array $data array of columns and values - * @param array $where array of columns and values + * @param object $where array of columns and values or string of query + * @param array $args params of query */ - public function update($table, $data, $where) + public function update($table, $data, $where, $args = []) { //collect the values from data and where $values = []; - + //setup fields $fieldDetails = null; foreach ($data as $key => $value) { @@ -212,16 +213,30 @@ public function update($table, $data, $where) //setup where $whereDetails = null; - $i = 0; - foreach ($where as $key => $value) { - $key = '`' . trim($key, '`') . '`'; - $whereDetails .= $i == 0 ? "$key = ?" : " AND $key = ?"; - $values[] = $value; - $i++; + if (is_string($where)) { + $where = trim($where); + $whereDetails = $where ?: ''; + $values = array_merge($values, $args); } - - $stmt = $this->run("UPDATE $table SET $fieldDetails WHERE $whereDetails", $values); - + else { + $i = 0; + foreach ($where as $key => $value) { + $key = '`' . trim($key, '`') . '`'; + $whereDetails .= $i == 0 ? "$key = ?" : " AND $key = ?"; + $values[] = $value; + $i++; + } + } + + // build SQL statement + $sql = "UPDATE $table SET $fieldDetails"; + if ($whereDetails) { + $sql .= " WHERE $whereDetails"; + } + + //execute query + $stmt = $this->run($sql, $values); + return $stmt->rowCount(); }