Commit 0c024935 authored by Josh's avatar Josh

Merge pull request #98 from avbdr/master

multiply features and bugfixes 
parents f7c16c85 dd5a93e5
This diff is collapsed.
<?php
require_once('MysqliDb.php');
error_reporting(E_ALL);
$action = 'adddb';
$data = array();
$db = new MysqliDb('localhost', 'root', 'root', 'db');
function printUsers () {
global $db;
$users = $db->get ("users");
if ($db->count == 0) {
echo "<td align=center colspan=4>No users found</td>";
return;
}
foreach ($users as $u) {
echo "<tr>
<td>{$u['id']}</td>
<td>{$u['login']}</td>
<td>{$u['firstName']} {$u['lastName']}</td>
<td>
<a href='index.php?action=rm&id={$u['id']}'>rm</a> ::
<a href='index.php?action=mod&id={$u['id']}'>ed</a>
</td>
</tr>";
}
}
function action_adddb () {
global $db;
$data = Array(
'login' => $_POST['login'],
'customerId' => 1,
'firstName' => $_POST['firstName'],
'lastName' => $_POST['lastName'],
'password' => $db->func('SHA1(?)',Array ($_POST['password'] . 'salt123')),
'createdAt' => $db->now(),
'expires' => $db->now('+1Y')
);
$id = $db->insert ('users', $data);
header ("Location: index.php");
exit;
}
function action_moddb () {
global $db;
$data = Array(
'login' => $_POST['login'],
'customerId' => 1,
'firstName' => $_POST['firstName'],
'lastName' => $_POST['lastName'],
);
$id = (int)$_POST['id'];
$db->where ("customerId",1);
$db->where ("id", $id);
$db->update ('users', $data);
header ("Location: index.php");
exit;
}
function action_rm () {
global $db;
$id = (int)$_GET['id'];
$db->where ("customerId",1);
$db->where ("id", $id);
$db->delete ('users');
header ("Location: index.php");
exit;
}
function action_mod () {
global $db;
global $data;
global $action;
$action = 'moddb';
$id = (int)$_GET['id'];
$db->where ("id", $id);
$data = $db->getOne ("users");
}
$db = new Mysqlidb ('localhost', 'root', '', 'testdb');
if ($_GET) {
$f = "action_".$_GET['action'];
if (function_exists ($f)) {
$f();
}
}
?>
<!DOCTYPE html>
......@@ -9,19 +94,32 @@ $db = new MysqliDb('localhost', 'root', 'root', 'db');
<html lang="en">
<head>
<meta charset="utf-8">
<title>untitled</title>
<title>Users</title>
</head>
<body>
<?php
$insertData = array(
'title' => 'Inserted title',
'body' => 'Inserted body'
);
$results = $db->insert('posts', $insertData);
print_r($results);
?>
<center>
<h3>Users:</h3>
<table width='50%'>
<tr bgcolor='#cccccc'>
<th>ID</th>
<th>Login</th>
<th>Name</th>
<th>Action</th>
</tr>
<?php printUsers();?>
</table>
<hr width=50%>
<form action='index.php?action=<?php echo $action?>' method=post>
<input type=hidden name='id' value='<?php echo $data['id']?>'>
<input type=text name='login' required placeholder='Login' value='<?php echo $data['login']?>'>
<input type=text name='firstName' required placeholder='First Name' value='<?php echo $data['firstName']?>'>
<input type=text name='lastName' required placeholder='Last Name' value='<?php echo $data['lastName']?>'>
<input type=password name='password' placeholder='Password'>
<input type=submit value='New User'></td>
<form>
</table>
</center>
</body>
</html>
......@@ -10,40 +10,80 @@ After that, create a new instance of the class.
$db = new Mysqlidb('host', 'username', 'password', 'databaseName');
```
It's also possible to set a table prefix:
```php
$db->setPrefix('tablePrefix');
```
Next, prepare your data, and call the necessary methods.
### Insert Query
Simple example
```php
$data = Array ("login" => "admin",
"firstName" => "John",
"lastName" => 'Doe'
)
$id = $db->insert('users', $data);
if($id)
echo 'user was created. Id='.$id;
```
Insert with functions use
```php
$data = array(
$data = Array(
'login' => 'admin',
'active' => true,
'firstName' => 'John',
'lastName' => 'Doe',
'password' => $db->func('SHA1(?)',Array ("secretpassword+salt")),
// password = SHA1('secretpassword+salt')
'createdAt' => $db->now(),
// createdAt = NOW()
'expires' => $db->now('+1Y')
// expires = NOW() + interval 1 year
// Supported intervals [s]econd, [m]inute, [h]hour, [d]day, [M]onth, [Y]ear
);
$id = $db->insert('users', $data)
$id = $db->insert('users', $data);
if($id)
echo 'user was created. Id='.$id;
```
### Select Query
### Update Query
```php
$data = Array (
'firstName' => 'Bobby',
'lastName' => 'Tables',
'editCount' => $db->inc(2),
// editCount = editCount + 2;
'active' => $db->not()
// active = !active;
);
$db->where('id', 1);
if($db->update('users', $data)) echo 'successfully updated';
```
### Select Query
After any select/get function calls amount or returned rows
is stored in $count variable
```php
$users = $db->get('users'); //contains an array of all users
$users = $db->get('users', 10); //contains an array 10 users
$users = $db->get('users'); //contains an Array of all users
$users = $db->get('users', 10); //contains an Array 10 users
```
or select with custom columns set. Functions also could be used
```php
$stats = $db->getOne ("users", null, "sum(id), count(*) as cnt");
$stats = $db->getOne ("users", "sum(id), count(*) as cnt");
echo "total ".$stats['cnt']. "users found";
$cols = Array ("id, name, email");
$users = $db->get ("users", null, $cols);
foreach ($users as $user) {
if ($db->count > 0)
foreach ($users as $user) {
print_r ($user);
}
}
```
or select just one row
......@@ -54,20 +94,10 @@ $user = $db->getOne ("users");
echo $user['id'];
```
### Update Query
```php
$data = array (
'firstName' => 'Bobby',
'lastName' => 'Tables'
);
$db->where('id', 1);
if($db->update('users', $data)) echo 'successfully updated';
```
### Delete Query
```php
$db->where('id', 1);
if($db->delete('posts')) echo 'successfully deleted';
if($db->delete('users')) echo 'successfully deleted';
```
### Generic Query Method
......@@ -80,14 +110,14 @@ foreach ($users as $user) {
### Raw Query Method
```php
$params = array(1, 'admin');
$params = Array(1, 'admin');
$users = $db->rawQuery("SELECT id, firstName, lastName FROM users WHERE id = ? AND login = ?", $params);
print_r($users); // contains array of returned rows
print_r($users); // contains Array of returned rows
// will handle any SQL query
$params = array(10, 1, 10, 11, 2, 10);
$params = Array(10, 1, 10, 11, 2, 10);
$resutls = $db->rawQuery("(SELECT a FROM t1 WHERE a = ? AND B = ? ORDER BY a LIMIT ?) UNION(SELECT a FROM t2 WHERE a = ? AND B = ? ORDER BY a LIMIT ?)", $params);
print_r($results); // contains array of returned rows
print_r($results); // contains Array of returned rows
```
......@@ -102,33 +132,63 @@ $results = $db->get('users');
// Gives: SELECT * FROM users WHERE id=1 AND login='admin';
```
Custom Operators:
```php
$db->where('id', array('>=' => 50));
$db->where('id', Array('>=' => 50));
$results = $db->get('users');
// Gives: SELECT * FROM users WHERE id >= 50;
```
BETWEEN:
```php
$db->where('id', array('between' => array(4, 20) ) );
$db->where('id', Array('between' => Array(4, 20) ) );
//$db->where('id', Array('not between' => Array(4, 20) ) );
$results = $db->get('users');
// Gives: SELECT * FROM users WHERE id BETWEEN 4 AND 20
```
IN:
```php
$db->where('id', array( 'in' => array(1, 5, 27, -1, 'd') ) );
$db->where('id', Array( 'in' => Array(1, 5, 27, -1, 'd') ) );
//$db->where('id', Array( 'not in' => Array(1, 5, 27, -1, 'd') ) );
$results = $db->get('users');
// Gives: SELECT * FROM users WHERE id IN (1, 5, 27, -1, 'd');
```
OR CASE
```php
$db->where('firstName','John');
$db->orWhere('firstName','Peter');
$results = $db->get('users');
// Gives: SELECT * FROM users WHERE firstName='John' OR firstName='peter'
```
NULL comparison:
```php
$db->where ("lastName", Array("<=>" => NULL));
$results = $db->get("users");
// Gives: SELECT * FROM users where lastName <=> NULL
```
Also you can use raw where conditions:
```php
$db->where ("id != companyId");
$results = $db->get("users");
```
Or raw condition with variables:
```php
$db->where("id = ? or id = ?", Array(6,2));
$res = $db->get ("users");
// Gives: SELECT * FROM users WERE id = 2 or id = 2;
```
Optionally you can use method chaining to call where multiple times without referencing your object over an over:
```php
$results = $db
->where('id', 1)
->where('title', 'MyTitle')
->where('login', 'admin')
->get('users');
```
......@@ -152,6 +212,18 @@ Join table products with table users with LEFT JOIN by tenantID
```php
$db->join("users u", "p.tenantID=u.tenantID", "LEFT");
$db->where("u.id", 6);
$products = $db->get ("products p", "u.name, p.productName");
$products = $db->get ("products p", null, "u.name, p.productName");
print_r ($products);
```
### Helper commands
Reconnect in case mysql connection died
```php
if (!$db->ping())
$db->connect()
```
Obtain an initialized instance of the class from another class
```php
$db = MysqliDb::getInstance();
```
<?php
require_once ("MysqliDb.php");
error_reporting(E_ALL);
$db = new Mysqlidb('localhost', 'root', '', 'testdb');
if(!$db) die("Database error");
$prefix = 't_';
$db->setPrefix($prefix);
$tables = Array (
'users' => Array (
'login' => 'char(10) not null',
'active' => 'bool default 0',
'customerId' => 'int(10) not null',
'firstName' => 'char(10) not null',
'lastName' => 'char(10)',
'password' => 'text not null',
'createdAt' => 'datetime',
'expires' => 'datetime',
'loginCount' => 'int(10) default 0'
),
'products' => Array (
'customerId' => 'int(10) not null',
'userId' => 'int(10) not null',
'productName' => 'char(50)'
)
);
$data = Array (
'users' => Array (
Array ('login' => 'user1',
'customerId' => 10,
'firstName' => 'John',
'lastName' => 'Doe',
'password' => $db->func('SHA1(?)',Array ("secretpassword+salt")),
'createdAt' => $db->now(),
'expires' => $db->now('+1Y'),
'loginCount' => $db->inc()
),
Array ('login' => 'user2',
'customerId' => 10,
'firstName' => 'Mike',
'lastName' => NULL,
'password' => $db->func('SHA1(?)',Array ("secretpassword2+salt")),
'createdAt' => $db->now(),
'expires' => $db->now('+1Y'),
'loginCount' => $db->inc(2)
),
Array ('login' => 'user3',
'active' => true,
'customerId' => 11,
'firstName' => 'Pete',
'lastName' => 'D',
'password' => $db->func('SHA1(?)',Array ("secretpassword2+salt")),
'createdAt' => $db->now(),
'expires' => $db->now('+1Y'),
'loginCount' => $db->inc(3)
)
),
'products' => Array (
Array ('customerId' => 1,
'userId' => 1,
'productName' => 'product1',
),
Array ('customerId' => 1,
'userId' => 1,
'productName' => 'product2',
),
Array ('customerId' => 1,
'userId' => 1,
'productName' => 'product3',
),
Array ('customerId' => 1,
'userId' => 2,
'productName' => 'product4',
),
Array ('customerId' => 1,
'userId' => 2,
'productName' => 'product5',
),
)
);
function createTable ($name, $data) {
global $db;
//$q = "CREATE TABLE $name (id INT(9) UNSIGNED PRIMARY KEY NOT NULL";
$q = "CREATE TABLE $name (id INT(9) UNSIGNED PRIMARY KEY AUTO_INCREMENT";
foreach ($data as $k => $v) {
$q .= ", $k $v";
}
$q .= ")";
$db->rawQuery($q);
}
foreach ($tables as $name => $fields) {
$db->rawQuery("DROP TABLE $name");
createTable ($prefix.$name, $fields);
}
foreach ($data as $name => $datas) {
foreach ($datas as $d) {
$id = $db->insert($name, $d);
if ($id)
$d['id'] = $id;
else {
echo "failed to insert: ".$db->getLastQuery() ."\n". $db->getLastError();
}
}
}
$db->orderBy("id","asc");
$users = $db->get("users");
if ($db->count != 3) {
echo "Invalid total insert count";
exit;
}
$db->where ("active", true);
$users = $db->get("users");
if ($db->count != 1) {
echo "Invalid total insert count with boolean";
exit;
}
$db->where ("active", false);
$db->update("users", Array ("active" => $db->not()));
$db->where ("active", true);
$users = $db->get("users");
if ($db->count != 3) {
echo "Invalid total insert count with boolean";
exit;
}
// TODO
//$db->where("createdAt", Array (">" => $db->interval("-1h")));
//$users = $db->get("users");
//print_r ($users);
$db->where("firstname", Array("LIKE" => '%John%'));
$users = $db->get("users");
if ($db->count != 1) {
echo "Invalid insert count in LIKE: ".$db->count;
print_r ($users);
echo $db->getLastQuery();
exit;
}
$db->groupBy("customerId");
$cnt = $db->get ("users", null, "customerId, count(id) as cnt");
if ($db->count != 2) {
echo "Invalid records count with group by";
}
$upData = Array (
'expires' => $db->now("+5M","expires"),
'loginCount' => $db->inc()
);
$db->where ("id", 1);
$cnt = $db->update("users", $upData);
$db->where ("id", 1);
$r = $db->getOne("users");
if ($db->count != 1) {
echo "Invalid users count on getOne()";
exit;
}
if ($r['password'] != '546f98b24edfdc3b9bbe0d241bd8b29783f71b32') {
echo "Invalid password were set".
exit;
}
$db->where ("id", Array('in' => Array('1','2','3')));
$db->get("users");
if ($db->count != 3) {
echo "Invalid users count on where() with in ";
exit;
}
$db->where ("id", Array('between' => Array('2','3')));
$db->get("users");
if ($db->count != 2) {
echo "Invalid users count on where() with between";
exit;
}
$db->where ("id", 2);
$db->orWhere ("customerId", 11);
$r = $db->get("users");
if ($db->count != 2) {
echo "Invalid users count on orWhere()";
exit;
}
$db->where ("lastName", Array("<=>" => NULL));
$r = $db->get("users");
if ($db->count != 1) {
echo "Invalid users count on null where()";
exit;
}
$db->join("users u", "p.userId=u.id", "LEFT");
$db->where("u.login",'user2');
$db->orderBy("CONCAT(u.login, u.firstName)");
$products = $db->get ("products p", null, "u.login, p.productName");
if ($db->count != 2) {
echo "Invalid products count on join ()";
exit;
}
$db->where("id = ? or id = ?", Array(1,2));
$res = $db->get ("users");
if ($db->count != 2) {
echo "Invalid users count on select with multiple params";
exit;
}
$db->delete("users");
$db->get("users");
if ($db->count != 0) {
echo "Invalid users count after delete";
exit;
}
$db->delete("products");
echo "All done";
//print_r($db->rawQuery("CALL simpleproc(?)",Array("test")));
?>
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment