Database - personaclix/PersonaClixEngine GitHub Wiki
Many applications require access to a database, so this class is here to make interacting with the database as easy and as hassle free as possible.
Constructor
Before calling the constructor, add a use statement to the top of the file.
use PersonaClix\Engine\Database;
The constructor takes 4 mandatory parameters with one optional parameter. A string for hostname, a string for username, a string for password, a string for database name, and an optional string or integer for port number (defaults to 3306). These will be used to form a connection to the database.
Only the MySQL Database Driver is supported at this time.
Upon connection failure, a PDOException message will be logged using PHP's error_log()
function.
$database = new Database( $host, $user, $pass, $name, $port );
select()
Perform a SELECT query.
Takes 3 parameters. The first parameter is an array of fields to select, the second parameter is a String containing the name of the table to select from, and the third and final parameter is an optional associative array to form the WHERE clause part of the query.
$results = $database->select( ['*'], 'some_table', ['column' => 'value', 'this' => 'that'] );
Returns an associative array of all results found or simply an empty array if none.
insert()
Insert a record into the database.
Takes 2 parameters. A string for the table name, and an associative array with Field Name => Value pairs.
$insert = $database->insert('list', ['title' => $title, 'description' => $description, 'price' => $price]);
Returns a boolean stating whether the query was successful or not.
update()
Update a record in the database.
Takes 2 mandatory parameters and 1 optional parameter. The table name as a string, the fields to update as an Associative Array, and an optional Associative Array to form a WHERE clause for limiting what gets updated.
$fields = [
'title' => 'New Title'
'description' => 'A changed description of the item.',
'price' => '1.00'
];
$where = [
'id' => '1'
];
$update = $database->update('list', $fields, $where);
Function will return a boolean stating whether the query was successful or not.
delete()
Delete all rows from a database table that match the specified WHERE clause. If no WHERE clause is specified, will truncate the table, which drops and re-creates it, making all auto-increments start at 1 again.
Truncating the table is a much faster way of deleting all records/rows from a table than simply running the delete command.
The function takes 2 parameters. A mandatory table name as a string, and an optional WHERE clause as an Associative Array of Field => Value pairs.
// Delete record with ID 1
$delete = $database->delete('list', ['id' => '1']);
Returns a boolean stating whether the query executed successfully or not.