From a308356c45fe4b010dc4fe9f2c13cbf7b3d7b7d2 Mon Sep 17 00:00:00 2001 From: se <6008932+se@users.noreply.github.com> Date: Mon, 17 Mar 2025 14:02:23 +0800 Subject: [PATCH] update with where --- src/Database.php | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/src/Database.php b/src/Database.php index bc77c12..f38bcaa 100644 --- a/src/Database.php +++ b/src/Database.php @@ -225,6 +225,46 @@ public function update($table, $data, $where) return $stmt->rowCount(); } + + /** + * update record + * + * @param string $table table name + * @param array $data array of columns and values + * @param string $where string of query + * @param array $args params of query + */ + public function updateByWhere($table, $data, $where, $args = []) + { + //collect the values from data and where + $values = []; + + //setup fields + $fieldDetails = ''; + foreach ($data as $key => $value) { + $key = '`' . trim($key, '`') . '`'; + $fieldDetails .= "$key = ?,"; + $values[] = $value; + } + $fieldDetails = rtrim($fieldDetails, ','); + + //setup where + $where = trim($where); + $whereDetails = $where ?: ''; + $values = array_merge($values, $args); + + // build SQL statement + $sql = "UPDATE $table SET $fieldDetails"; + if ($whereDetails) { + $sql .= " WHERE $whereDetails"; + } + + //execute query + $stmt = $this->run($sql, $values); + + return $stmt->rowCount(); + } + /** * Delete records *