MySQLi wrapper for PHP.
, (*1)
Requirements
- MySQL 5.5 or newer.
- PHP 5.4 or newer.
Installation
Install the latest version with:, (*2)
$ composer require jrdev/mysql
How to use
First, connect to a database:, (*3)
$db = new \jrdev\MySQL('host', 'user', 'pass', 'database');
Next, prepare your data, and call the necessary methods., (*4)
Generic query method
This method accepts only one param, the SQL to execute.
And returns a jrdev\MySQL\Result object., (*5)
$query = $db->query('SELECT ...');
A SELECT statement
This method accepts:, (*6)
-
tableName
: The name of the table.
-
fields
: (Optional) The fields you want to obtain in the result. Accepts array or string
-
where
: (Optional) The where. Accepts array, string or intenger
-
orderBy
(Optional) The order by.
-
limit
(Optional) The limit.
Returns a jrdev\MySQL\Result object., (*7)
$query = $db->select('table_name', 'field1, field2');
if ($query)
{
echo 'Num Rows: ', $query->num_rows, '<br>';
foreach ($query as $row)
{
echo $row['first_name'], '<br>';
}
}
else
{
echo $db->error();
}
// The $where (third param) accepts array, string or integer:
$query = $db->select('table_name', 'field1', ['name' => 'Pepe']); // With array.
$query = $db->select('table_name', 'field1', 'name = "Pepe"'); // With string.
$query = $db->select('table_name', 'field1', 1); // With integer. In this case, the resulting sql for the "WHERE" is "id = 1".
An INSERT statement
This method accepts:, (*8)
-
tableName
: The name of the table.
-
fields
: The fields you want to insert.
Returns the ID of the inserted row, or FALSE on error., (*9)
$inserted_id = $db->insert('table_name', [
'field1' => 'Value 1',
'field2' => 2,
]);
An UPDATE statement
This method accepts:, (*10)
-
tableName
: The name of the table.
-
fields
: The fields to update.
-
where
: The where. Accepts array, string or intenger.
-
limit
(Optional) The limit of rows to update.
Returns the number of affected rows, or FALSE on error., (*11)
// NOTE: The $where (third param) like the select method accepts array, string or integer.
$row = [
'field1' => 'Value',
];
$updated_rows = $db->update('table_name', $row, ['id' => 58]); // With array.
$updated_rows = $db->update('table_name', $row, 'id=58'); // With string.
$updated_rows = $db->update('table_name', $row, 58); // With integer.
A DELETE statement
This method accepts:, (*12)
-
tableName
: The name of the table.
-
where
: The where. Accepts array, string or intenger.
-
limit
(Optional) The limit of rows to delete.
Returns the number of affected rows, or FALSE on error., (*13)
// NOTE: The $where (second param) like the select method accepts array, string or integer.
$deleted_rows = $db->delete('table_name', ['id' => 58]); // With array.
$deleted_rows = $db->delete('table_name', 'id=58'); // With string.
$deleted_rows = $db->delete('table_name', 58); // With integer.
License
Licensed under the MIT licence., (*14)