-
Notifications
You must be signed in to change notification settings - Fork 3
How to Use: Manipulating Data
The backbone of GrumpyPDO is it's run()
method. This method is essentially the same as running query()
/prepare()
and executing the query at the same time in native PDO
. It allows you to write any kind of query you need, and pass the values to it at the same time.
This method also supports multiple data sets.
Here is a few examples of how this method can be used. This method returns a PDOStatement Object, which can be used just like native PDO
to do whatever you need to do, so if you are most comfortable using PDO the same as you would natively, you could use this method to skip the step of executing the query separately.
Here are some methods intended to make fetching data easier than using this method for basic queries.
$db->run("DELETE FROM users WHERE id=?", array(4));
//single update data
$db->run("UPDATE users SET name=? WHERE id=?", array("Updated Name", 2));
//multi data update
$updates = [
['name' => 'Updated Name 1', 'uid' => 2],
['name' => 'Updated Name 2', 'uid' => 4]
];
$db->run("UPDATE users SET name=:name WHERE uid=:uid", $updates);
//single data insert
$db->run("INSERT INTO users (name) VALUES (?)", ['New Name']);
//multi data insert
$inserts = [
['name' => "New Name 1"],
['name' => "New Name 2"]
];
$db->run("INSERT INTO users (name) VALUES (:name)", $inserts);
The insert method allows you to insert data into a table using only the table name and an array of data.
Since this method accepts a table name and database columns that may come from a user, thus is unsafe, we also run 2 extra queries when running the insert method. These queries verify the table name exists in the currently connected database, and also makes sure the columns passed to the query exist in the given table name.
$values = [
'name' => 'Example Name'
];
$db->insert('users', $values);
Inserting this way is the most effecient way to insert multiple records at once. This will prepare the statement once, and execute each set against that single prepare.
$values = [
['name' => 'Example Name 1'],
['name' => 'Example Name 2']
];
$db->insert('users', $values);
The update method allows you to perform basic update operations on a single table at a time. It's not very useful for more advanced updates.
All $where
conditions are separated by AND
.
Since this method accepts a table name and database columns that may come from a user, thus is unsafe, we also run 2 extra queries when running the insert method. These queries verify the table name exists in the currently connected database, and also makes sure the columns passed to the query exist in the given table name.
Note: This method does not support multiple data sets
$updates = [
"name" => "Updated Name"
];
$where = [
"id" => 2
];
$db->update('users', $updates, $where);