Skip to content

Commit 67c85f9

Browse files
authored
Merge pull request #5 from jr-cologne/jr_improve_update_method
Improve update() method and sql queries in example
2 parents de78f65 + 0baae91 commit 67c85f9

File tree

3 files changed

+17
-4
lines changed

3 files changed

+17
-4
lines changed

DB.php

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -161,13 +161,17 @@ public function update(string $sql, array $values) {
161161
$statement = $pdo->prepare($sql);
162162

163163
$execution = $statement->execute($values);
164+
165+
$affected_rows = $statement->rowCount();
164166
} catch (PDOException $e) {
165167
$this->error = [ 'code' => 5, 'msg' => $error_types[5], 'pdo_exception' => $e ];
166168
return $this->getError();
167169
}
168170

169-
if ($execution) {
171+
if ($execution && $affected_rows > 0) {
170172
return true;
173+
} else if ($execution && $affected_rows == 0) {
174+
return 0;
171175
} else {
172176
return false;
173177
}

README.md

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -232,6 +232,15 @@ You can update data in your database by the method `update()`, which has this fo
232232
update(string $sql, array $values)
233233
```
234234

235+
The method has the following return values:
236+
237+
`true`: Everything has been updated successfully
238+
239+
`0`: The query has been executed successfully, but no rows have been affected by it.
240+
241+
`false`: The query is completely failed.
242+
243+
235244
That leads to the following arguments:
236245

237246
#### SQL Query (`$sql`)

example.php

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@
2525
echo 'You are successfully connected to the database!<br><br>';
2626

2727
for ($i=1; $i <= 10; $i++) {
28-
$inserted[] = $db->insert("INSERT INTO users (id, username, password) VALUES (:id, :username, :password)", [ 'id' => $i, 'username' => 'test' . $i, 'password' => 'hello' . $i ]);
28+
$inserted[] = $db->insert("INSERT INTO `users` (id, username, password) VALUES (:id, :username, :password)", [ 'id' => $i, 'username' => 'test' . $i, 'password' => 'hello' . $i ]);
2929
}
3030

3131
$data_inserted = 0;
@@ -42,7 +42,7 @@
4242
echo 'Some errors are occured when trying to insert data to the database.<br><br>';
4343
}
4444

45-
$data = $db->select("SELECT * FROM users");
45+
$data = $db->select("SELECT * FROM `users`");
4646

4747
if (!empty($data)) {
4848
echo 'Your data:<br><br>';
@@ -51,7 +51,7 @@
5151
echo 'An error is occured when trying to get your data from the database or there is no data.<br><br>';
5252
}
5353

54-
$deleted = $db->delete("DELETE FROM users");
54+
$deleted = $db->delete("DELETE FROM `users`");
5555

5656
if ($deleted === true) {
5757
echo 'Your data has been successfully deleted from the database.<br><br>';

0 commit comments

Comments
 (0)