Commit 0a03d83b authored by screeper's avatar screeper

Merge pull request #1 from avbdr/master

Merge from avbdr
parents 231fa1dc fee1b126
This diff is collapsed.
<?php <?php
require_once('MysqliDb.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> <!DOCTYPE html>
...@@ -9,19 +94,32 @@ $db = new MysqliDb('localhost', 'root', 'root', 'db'); ...@@ -9,19 +94,32 @@ $db = new MysqliDb('localhost', 'root', 'root', 'db');
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
<title>untitled</title> <title>Users</title>
</head> </head>
<body> <body>
<?php
$insertData = array(
'title' => 'Inserted title',
'body' => 'Inserted body'
);
$results = $db->insert('posts', $insertData); <center>
print_r($results); <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> </body>
</html> </html>
\ No newline at end of file
...@@ -19,7 +19,7 @@ $data = Array ("login" => "admin", ...@@ -19,7 +19,7 @@ $data = Array ("login" => "admin",
"firstName" => "John", "firstName" => "John",
"lastName" => 'Doe' "lastName" => 'Doe'
) )
$id = $db->insert('users', $data) $id = $db->insert('users', $data);
if($id) if($id)
echo 'user was created. Id='.$id; echo 'user was created. Id='.$id;
``` ```
...@@ -28,6 +28,7 @@ Insert with functions use ...@@ -28,6 +28,7 @@ Insert with functions use
```php ```php
$data = Array( $data = Array(
'login' => 'admin', 'login' => 'admin',
'active' => true,
'firstName' => 'John', 'firstName' => 'John',
'lastName' => 'Doe', 'lastName' => 'Doe',
'password' => $db->func('SHA1(?)',Array ("secretpassword+salt")), 'password' => $db->func('SHA1(?)',Array ("secretpassword+salt")),
...@@ -39,7 +40,7 @@ $data = Array( ...@@ -39,7 +40,7 @@ $data = Array(
// Supported intervals [s]econd, [m]inute, [h]hour, [d]day, [M]onth, [Y]ear // 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) if($id)
echo 'user was created. Id='.$id; echo 'user was created. Id='.$id;
``` ```
...@@ -51,8 +52,8 @@ $data = Array ( ...@@ -51,8 +52,8 @@ $data = Array (
'lastName' => 'Tables', 'lastName' => 'Tables',
'editCount' => $db->inc(2), 'editCount' => $db->inc(2),
// editCount = editCount + 2; // editCount = editCount + 2;
'editBoolean' => $db->not() 'active' => $db->not()
// editBoolean = !editBoolean; // active = !active;
); );
$db->where('id', 1); $db->where('id', 1);
if($db->update('users', $data)) echo 'successfully updated'; if($db->update('users', $data)) echo 'successfully updated';
...@@ -91,7 +92,7 @@ echo $user['id']; ...@@ -91,7 +92,7 @@ echo $user['id'];
### Delete Query ### Delete Query
```php ```php
$db->where('id', 1); $db->where('id', 1);
if($db->delete('posts')) echo 'successfully deleted'; if($db->delete('users')) echo 'successfully deleted';
``` ```
### Generic Query Method ### Generic Query Method
...@@ -126,7 +127,6 @@ $results = $db->get('users'); ...@@ -126,7 +127,6 @@ $results = $db->get('users');
// Gives: SELECT * FROM users WHERE id=1 AND login='admin'; // Gives: SELECT * FROM users WHERE id=1 AND login='admin';
``` ```
Custom Operators:
```php ```php
$db->where('id', Array('>=' => 50)); $db->where('id', Array('>=' => 50));
$results = $db->get('users'); $results = $db->get('users');
...@@ -136,6 +136,7 @@ $results = $db->get('users'); ...@@ -136,6 +136,7 @@ $results = $db->get('users');
BETWEEN: BETWEEN:
```php ```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'); $results = $db->get('users');
// Gives: SELECT * FROM users WHERE id BETWEEN 4 AND 20 // Gives: SELECT * FROM users WHERE id BETWEEN 4 AND 20
``` ```
...@@ -143,6 +144,7 @@ $results = $db->get('users'); ...@@ -143,6 +144,7 @@ $results = $db->get('users');
IN: IN:
```php ```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'); $results = $db->get('users');
// Gives: SELECT * FROM users WHERE id IN (1, 5, 27, -1, 'd'); // Gives: SELECT * FROM users WHERE id IN (1, 5, 27, -1, 'd');
``` ```
...@@ -162,12 +164,26 @@ $results = $db->get("users"); ...@@ -162,12 +164,26 @@ $results = $db->get("users");
// Gives: SELECT * FROM users where lastName <=> NULL // 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: Optionally you can use method chaining to call where multiple times without referencing your object over an over:
```php ```php
$results = $db $results = $db
->where('id', 1) ->where('id', 1)
->where('title', 'MyTitle') ->where('login', 'admin')
->get('users'); ->get('users');
``` ```
...@@ -194,3 +210,15 @@ $db->where("u.id", 6); ...@@ -194,3 +210,15 @@ $db->where("u.id", 6);
$products = $db->get ("products p", null, "u.name, p.productName"); $products = $db->get ("products p", null, "u.name, p.productName");
print_r ($products); 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();
```
...@@ -8,6 +8,7 @@ if(!$db) die("Database error"); ...@@ -8,6 +8,7 @@ if(!$db) die("Database error");
$tables = Array ( $tables = Array (
'users' => Array ( 'users' => Array (
'login' => 'char(10) not null', 'login' => 'char(10) not null',
'active' => 'bool default 0',
'customerId' => 'int(10) not null', 'customerId' => 'int(10) not null',
'firstName' => 'char(10) not null', 'firstName' => 'char(10) not null',
'lastName' => 'char(10)', 'lastName' => 'char(10)',
...@@ -15,37 +16,67 @@ $tables = Array ( ...@@ -15,37 +16,67 @@ $tables = Array (
'createdAt' => 'datetime', 'createdAt' => 'datetime',
'expires' => 'datetime', 'expires' => 'datetime',
'loginCount' => 'int(10) default 0' 'loginCount' => 'int(10) default 0'
),
'products' => Array (
'customerId' => 'int(10) not null',
'userId' => 'int(10) not null',
'productName' => 'char(50)'
) )
); );
$data = Array ( $data = Array (
Array ('login' => 'user1', 'users' => Array (
'customerId' => 10, Array ('login' => 'user1',
'firstName' => 'John', 'customerId' => 10,
'lastName' => 'Doe', 'firstName' => 'John',
'password' => $db->func('SHA1(?)',Array ("secretpassword+salt")), 'lastName' => 'Doe',
'createdAt' => $db->now(), 'password' => $db->func('SHA1(?)',Array ("secretpassword+salt")),
'expires' => $db->now('+1Y'), 'createdAt' => $db->now(),
'loginCount' => $db->inc() 'expires' => $db->now('+1Y'),
), 'loginCount' => $db->inc()
Array ('login' => 'user2', ),
'customerId' => 10, Array ('login' => 'user2',
'firstName' => 'Mike', 'customerId' => 10,
'lastName' => NULL, 'firstName' => 'Mike',
'password' => $db->func('SHA1(?)',Array ("secretpassword2+salt")), 'lastName' => NULL,
'createdAt' => $db->now(), 'password' => $db->func('SHA1(?)',Array ("secretpassword2+salt")),
'expires' => $db->now('+1Y'), 'createdAt' => $db->now(),
'loginCount' => $db->inc(2) '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)
)
), ),
Array ('login' => 'user3', 'products' => Array (
'customerId' => 11, Array ('customerId' => 1,
'firstName' => 'Pete', 'userId' => 1,
'lastName' => 'D', 'productName' => 'product1',
'password' => $db->func('SHA1(?)',Array ("secretpassword2+salt")), ),
'createdAt' => $db->now(), Array ('customerId' => 1,
'expires' => $db->now('+1Y'), 'userId' => 1,
'loginCount' => $db->inc(3) '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) { function createTable ($name, $data) {
...@@ -64,12 +95,15 @@ foreach ($tables as $name => $fields) { ...@@ -64,12 +95,15 @@ foreach ($tables as $name => $fields) {
createTable ($name, $fields); createTable ($name, $fields);
} }
foreach ($data as $d) {
$id = $db->insert("users", $d); foreach ($data as $name => $datas) {
if ($id) foreach ($datas as $d) {
$d['id'] = $id; $id = $db->insert($name, $d);
else { if ($id)
echo "failed to insert: ".$db->getLastQuery() ."\n". $db->getLastError(); $d['id'] = $id;
else {
echo "failed to insert: ".$db->getLastQuery() ."\n". $db->getLastError();
}
} }
} }
...@@ -79,6 +113,23 @@ if ($db->count != 3) { ...@@ -79,6 +113,23 @@ if ($db->count != 3) {
echo "Invalid total insert count"; echo "Invalid total insert count";
exit; 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 // TODO
//$db->where("createdAt", Array (">" => $db->interval("-1h"))); //$db->where("createdAt", Array (">" => $db->interval("-1h")));
//$users = $db->get("users"); //$users = $db->get("users");
...@@ -147,12 +198,29 @@ if ($db->count != 1) { ...@@ -147,12 +198,29 @@ if ($db->count != 1) {
exit; 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->delete("users");
$db->get("users"); $db->get("users");
if ($db->count != 0) { if ($db->count != 0) {
echo "Invalid users count after delete"; echo "Invalid users count after delete";
exit; exit;
} }
$db->delete("products");
echo "All done"; echo "All done";
//print_r($db->rawQuery("CALL simpleproc(?)",Array("test"))); //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