16 Commits
v2.2.0 ... v2.3

Author SHA1 Message Date
Sergey Tsalkov
eb36858f1a columnList() properly escapes table names 2014-06-16 22:40:22 +00:00
Sergey Tsalkov
1d797b306e bugfix: insert/update type functions don't break when using a param_char other than % 2014-06-14 02:41:06 +00:00
Sergey Tsalkov
7c819bfc24 the connect_options variable lets you set mysqli_options, like a connection timeout 2014-06-14 01:58:51 +00:00
Sergey Tsalkov
1d147e169a ssl support (still untested) 2014-06-14 01:31:32 +00:00
Sergey Tsalkov
391702700d clean up static class init syntax a bit 2014-06-14 01:06:05 +00:00
Sergey Tsalkov
37fd169be3 minor bugfix: don't assume that the query results for queryFirstRow() or queryFirstList() will be an array (can also be a bool) 2014-06-14 00:27:38 +00:00
Sergey Tsalkov
7c5c03c576 minor cleanups 2014-06-13 21:19:10 +00:00
Sergey Tsalkov
a0a2f702e2 bugfix: don't crash if nested transactions are enabled, and the first command issued is a start transaction 2014-03-31 01:50:10 -07:00
Sergey Tsalkov
2707bcba7d minor bugfix: don't drop identical query components in WhereClause (thanks Alexander!) 2013-12-06 11:17:54 -08:00
Sergey Tsalkov
7b0da839de add yet another test for this weird bug people are reporting
tests *still* all pass, I can't reproduce the bug
2013-11-08 14:14:46 -08:00
Sergey Tsalkov
1d51c2b674 add additional test case for a reported bug where '%s' in data is parsed as a query placeholder
I can't reproduce the bug
2013-09-13 22:36:33 -07:00
SergeyTsalkov
de63573e98 Merge pull request #14 from bcash/master
Added passthru of mysqli error code to MeekroDBException object
2013-06-30 01:31:12 -07:00
Brian Cash
26fcce650a Passes mysqli error code to MeekroDBException 2013-06-22 11:56:01 -07:00
Sergey Tsalkov
e403c774c8 Merge branch 'master' of github.com:SergeyTsalkov/meekrodb 2013-06-21 16:27:25 -07:00
Sergey Tsalkov
740ca7bc67 restore %ss to working, add unit test so it won't break again 2013-06-21 16:27:05 -07:00
SergeyTsalkov
7563c660ad Update readme to include brief installation section 2013-06-09 17:08:20 -06:00
10 changed files with 113 additions and 39 deletions

View File

@@ -8,6 +8,27 @@ MeekroDB is:
* Google's #1 search result for "php mysql library" for over 2 years, with **thousands of deployments worldwide**.
* A library with a **perfect security track record**. No bugs relating to security or SQL injection have ever been discovered.
Installation
========
When you're ready to get started, see the [Quick Start Guide](http://www.meekro.com/quickstart.php) on our website.
### Manual Setup
Include the `db.class.php` file into your project and set it up like this:
require_once 'db.class.php';
DB::$user = 'my_database_user';
DB::$password = 'my_database_password';
DB::$dbName = 'my_database_name';
### Composer
Add this to your `composer.json`
{
"require": {
"sergeytsalkov/meekrodb": "*"
}
}
Code Examples
========
### Grab some rows from the database and print out a field from each row.

View File

@@ -36,6 +36,8 @@ class DB {
public static $throw_exception_on_nonsql_error = false;
public static $nested_transactions = false;
public static $usenull = true;
public static $ssl = array('key' => '', 'cert' => '', 'ca_cert' => '', 'ca_path' => '', 'cipher' => '');
public static $connect_options = array(MYSQLI_OPT_CONNECT_TIMEOUT => 30);
// internal
protected static $mdb = null;
@@ -47,19 +49,21 @@ class DB {
$mdb = DB::$mdb = new MeekroDB();
}
if ($mdb->param_char !== DB::$param_char) $mdb->param_char = DB::$param_char;
if ($mdb->named_param_seperator !== DB::$named_param_seperator) $mdb->named_param_seperator = DB::$named_param_seperator;
if ($mdb->success_handler !== DB::$success_handler) $mdb->success_handler = DB::$success_handler;
if ($mdb->error_handler !== DB::$error_handler) $mdb->error_handler = DB::$error_handler;
if ($mdb->throw_exception_on_error !== DB::$throw_exception_on_error) $mdb->throw_exception_on_error = DB::$throw_exception_on_error;
if ($mdb->nonsql_error_handler !== DB::$nonsql_error_handler) $mdb->nonsql_error_handler = DB::$nonsql_error_handler;
if ($mdb->throw_exception_on_nonsql_error !== DB::$throw_exception_on_nonsql_error) $mdb->throw_exception_on_nonsql_error = DB::$throw_exception_on_nonsql_error;
if ($mdb->nested_transactions !== DB::$nested_transactions) $mdb->nested_transactions = DB::$nested_transactions;
if ($mdb->usenull !== DB::$usenull) $mdb->usenull = DB::$usenull;
static $variables_to_sync = array('param_char', 'named_param_seperator', 'success_handler', 'error_handler', 'throw_exception_on_error',
'nonsql_error_handler', 'throw_exception_on_nonsql_error', 'nested_transactions', 'usenull', 'ssl', 'connect_options');
$db_class_vars = get_class_vars('DB'); // the DB::$$var syntax only works in 5.3+
foreach ($variables_to_sync as $variable) {
if ($mdb->$variable !== $db_class_vars[$variable]) {
$mdb->$variable = $db_class_vars[$variable];
}
}
return $mdb;
}
// yes, this is ugly. __callStatic() only works in 5.3+
public static function get() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'get'), $args); }
public static function disconnect() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'disconnect'), $args); }
public static function query() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'query'), $args); }
@@ -127,6 +131,8 @@ class MeekroDB {
public $throw_exception_on_nonsql_error = false;
public $nested_transactions = false;
public $usenull = true;
public $ssl = array('key' => '', 'cert' => '', 'ca_cert' => '', 'ca_path' => '', 'cipher' => '');
public $connect_options = array(MYSQLI_OPT_CONNECT_TIMEOUT => 30);
// internal
public $internal_mysql = null;
@@ -160,7 +166,19 @@ class MeekroDB {
if (!($mysql instanceof MySQLi)) {
if (! $this->port) $this->port = ini_get('mysqli.default_port');
$this->current_db = $this->dbName;
$mysql = new mysqli($this->host, $this->user, $this->password, $this->dbName, $this->port);
$mysql = new mysqli();
$connect_flags = 0;
if ($this->ssl['key']) {
$mysql->ssl_set($this->ssl['key'], $this->ssl['cert'], $this->ssl['ca_cert'], $this->ssl['ca_path'], $this->ssl['cipher']);
$connect_flags |= MYSQLI_CLIENT_SSL;
}
foreach ($this->connect_options as $key => $value) {
$mysql->options($key, $value);
}
// suppress warnings, since we will check connect_error anyway
@$mysql->real_connect($this->host, $this->user, $this->password, $this->dbName, $this->port, null, $connect_flags);
if ($mysql->connect_error) {
$this->nonSQLError('Unable to connect to MySQL server! Error: ' . $mysql->connect_error);
@@ -201,7 +219,7 @@ class MeekroDB {
$this->success_handler = $handler;
}
public function serverVersion() { return $this->server_info; }
public function serverVersion() { $this->get(); return $this->server_info; }
public function transactionDepth() { return $this->nested_transactions_count; }
public function insertId() { return $this->insert_id; }
public function affectedRows() { return $this->affected_rows; }
@@ -281,7 +299,7 @@ class MeekroDB {
$params = array_shift($args);
$where = array_shift($args);
$query = "UPDATE %b SET %? WHERE " . $where;
$query = str_replace('%', $this->param_char, "UPDATE %b SET %? WHERE ") . $where;
array_unshift($args, $params);
array_unshift($args, $table);
@@ -309,17 +327,23 @@ class MeekroDB {
if (isset($options['update']) && is_array($options['update']) && $options['update'] && strtolower($which) == 'insert') {
if (array_values($options['update']) !== $options['update']) {
return $this->query("INSERT INTO %b %lb VALUES %? ON DUPLICATE KEY UPDATE %?", $table, $keys, $values, $options['update']);
return $this->query(
str_replace('%', $this->param_char, "INSERT INTO %b %lb VALUES %? ON DUPLICATE KEY UPDATE %?"),
$table, $keys, $values, $options['update']);
} else {
$update_str = array_shift($options['update']);
$query_param = array("INSERT INTO %b %lb VALUES %? ON DUPLICATE KEY UPDATE $update_str", $table, $keys, $values);
$query_param = array(
str_replace('%', $this->param_char, "INSERT INTO %b %lb VALUES %? ON DUPLICATE KEY UPDATE ") . $update_str,
$table, $keys, $values);
$query_param = array_merge($query_param, $options['update']);
return call_user_func_array(array($this, 'query'), $query_param);
}
}
return $this->query("%l INTO %b %lb VALUES %?", $which, $table, $keys, $values);
return $this->query(
str_replace('%', $this->param_char, "%l INTO %b %lb VALUES %?"),
$which, $table, $keys, $values);
}
public function insert($table, $data) { return $this->insertOrReplace('INSERT', $table, $data); }
@@ -361,7 +385,7 @@ class MeekroDB {
}
public function columnList($table) {
return $this->queryOneColumn('Field', "SHOW COLUMNS FROM $table");
return $this->queryOneColumn('Field', "SHOW COLUMNS FROM %b", $table);
}
public function tableList($db = null) {
@@ -539,7 +563,7 @@ class MeekroDB {
else if ($type == 'd') $result = doubleval($arg);
else if ($type == 'b') $result = $this->formatTableName($arg);
else if ($type == 'l') $result = $arg;
else if ($type == 'ss') $result = "%" . $this->escape(str_replace(array('%', '_'), array('\%', '\_'), $arg)) . "%";
else if ($type == 'ss') $result = $this->escape("%" . str_replace(array('%', '_'), array('\%', '\_'), $arg) . "%");
else if ($type == 't') $result = $this->escape($this->parseTS($arg));
else if ($type == 'ls') $result = array_map(array($this, 'escape'), $arg);
@@ -614,12 +638,13 @@ class MeekroDB {
call_user_func($error_handler, array(
'type' => 'sql',
'query' => $sql,
'error' => $db->error
'error' => $db->error,
'code' => $db->errno
));
}
if ($this->throw_exception_on_error) {
$e = new MeekroDBException($db->error, $sql);
$e = new MeekroDBException($db->error, $sql, $db->errno);
throw $e;
}
} else if ($this->success_handler) {
@@ -673,7 +698,7 @@ class MeekroDB {
public function queryFirstRow() {
$args = func_get_args();
$result = call_user_func_array(array($this, 'query'), $args);
if (! $result) return null;
if (!$result || !is_array($result)) return null;
return reset($result);
}
@@ -681,7 +706,7 @@ class MeekroDB {
public function queryFirstList() {
$args = func_get_args();
$result = call_user_func_array(array($this, 'queryAllLists'), $args);
if (! $result) return null;
if (!$result || !is_array($result)) return null;
return reset($result);
}
@@ -789,12 +814,11 @@ class WhereClause {
}
function textAndArgs() {
$sql = '';
$sql = array();
$args = array();
if (count($this->clauses) == 0) return array('(1)', $args);
$sql = array();
foreach ($this->clauses as $clause) {
if ($clause instanceof WhereClause) {
list($clause_sql, $clause_args) = $clause->textAndArgs();
@@ -807,7 +831,6 @@ class WhereClause {
$args = array_merge($args, $clause_args);
}
$sql = array_unique($sql);
if ($this->type == 'and') $sql = implode(' AND ', $sql);
else $sql = implode(' OR ', $sql);
@@ -840,9 +863,10 @@ class DBTransaction {
class MeekroDBException extends Exception {
protected $query = '';
function __construct($message='', $query='') {
function __construct($message='', $query='', $code = 0) {
parent::__construct($message);
$this->query = $query;
$this->code = $code;
}
public function getQuery() { return $this->query; }

View File

@@ -2,7 +2,7 @@
class BasicTest extends SimpleTest {
function __construct() {
foreach (DB::tableList() as $table) {
DB::query("DROP TABLE $table");
DB::query("DROP TABLE %b", $table);
}
}
@@ -114,6 +114,8 @@ class BasicTest extends SimpleTest {
$bart = DB::queryFirstRow("SELECT * FROM accounts WHERE age IN ###li AND height IN ###ld AND username IN ###ls",
array(15, 25), array(10.371, 150.123), array('Bart', 'Barts'));
$this->assert($bart['username'] === 'Bart');
DB::insert('accounts', array('username' => 'f_u'));
DB::query("DELETE FROM accounts WHERE username=###s", 'f_u');
DB::$param_char = '%';
$charlie_password = DB::queryFirstField("SELECT password FROM accounts WHERE username IN %ls AND username = %s",
@@ -256,7 +258,7 @@ class BasicTest extends SimpleTest {
$this->assert($rows[1]['password'] === 'somethingelse');
$this->assert($rows[1]['username'] === '2ofmany');
$nullrow = DB::queryOneRow("SELECT * FROM accounts WHERE username=%s", '3ofmany');
$nullrow = DB::queryOneRow("SELECT * FROM accounts WHERE username LIKE %ss", '3ofman');
$this->assert($nullrow['password'] === NULL);
$this->assert($nullrow['age'] === '15');
}
@@ -264,20 +266,24 @@ class BasicTest extends SimpleTest {
function test_5_insert_blobs() {
DB::query("CREATE TABLE `storedata` (
DB::query("CREATE TABLE `store data` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`picture` BLOB
) ENGINE = InnoDB");
$columns = DB::columnList('store data');
$this->assert(count($columns) === 2);
$this->assert($columns[1] === 'picture');
$smile = file_get_contents('smile1.jpg');
DB::insert('storedata', array(
DB::insert('store data', array(
'picture' => $smile,
));
DB::query("INSERT INTO storedata (picture) VALUES (%s)", $smile);
DB::queryOneRow("INSERT INTO %b (picture) VALUES (%s)", 'store data', $smile);
$getsmile = DB::queryFirstField("SELECT picture FROM storedata WHERE id=1");
$getsmile2 = DB::queryFirstField("SELECT picture FROM storedata WHERE id=2");
$getsmile = DB::queryFirstField("SELECT picture FROM %b WHERE id=1", 'store data');
$getsmile2 = DB::queryFirstField("SELECT picture FROM %b WHERE id=2", 'store data');
$this->assert($smile === $getsmile);
$this->assert($smile === $getsmile2);
}
@@ -394,6 +400,20 @@ class BasicTest extends SimpleTest {
$this->assert($r[0]['1+1'] === '2');
}
function test_901_updatewithspecialchar() {
$data = 'www.mysite.com/product?s=t-%s-%%3d%%3d%i&RCAID=24322';
DB::update('profile', array('signature' => $data), 'id=%i', 1);
$signature = DB::queryFirstField("SELECT signature FROM profile WHERE id=%i", 1);
$this->assert($signature === $data);
DB::update('profile',array('signature'=> "%li "),"id = %d",1);
$signature = DB::queryFirstField("SELECT signature FROM profile WHERE id=%i", 1);
$this->assert($signature === "%li ");
}
}

View File

@@ -1,4 +1,4 @@
<?
<?php
function new_error_callback($params) {
global $error_callback_worked;

View File

@@ -1,4 +1,4 @@
<?
<?php
class ErrorTest_53 extends SimpleTest {
function test_1_error_handler() {
global $anonymous_error_callback_worked;

View File

@@ -1,4 +1,4 @@
<?
<?php
class HelperTest extends SimpleTest {
function test_1_verticalslice() {
$all = DB::query("SELECT * FROM accounts ORDER BY id ASC");

View File

@@ -6,7 +6,7 @@ class ObjectTest extends SimpleTest {
$this->mdb = new MeekroDB();
foreach ($this->mdb->tableList() as $table) {
$this->mdb->query("DROP TABLE $table");
$this->mdb->query("DROP TABLE %b", $table);
}
}

View File

@@ -1,4 +1,4 @@
<?
<?php
class TransactionTest extends SimpleTest {
function test_1_transactions() {
DB::$nested_transactions = false;

View File

@@ -1,4 +1,4 @@
<?
<?php
class TransactionTest_55 extends SimpleTest {
function test_1_transactions() {
DB::$nested_transactions = true;

View File

@@ -1,4 +1,4 @@
<?
<?php
class WhereClauseTest extends SimpleTest {
function test_1_basic_where() {
$where = new WhereClause('and');
@@ -57,6 +57,15 @@ class WhereClauseTest extends SimpleTest {
$this->assert(count($result) === 1);
$this->assert($result[0]['age'] === '15');
}
function test_6_or() {
$where = new WhereClause('or');
$where->add('username=%s', 'Bart');
$where->add('username=%s', 'Abe');
$result = DB::query("SELECT * FROM accounts WHERE %l", $where);
$this->assert(count($result) === 2);
}
}