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
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>
......@@ -19,7 +19,7 @@ $data = Array ("login" => "admin",
"firstName" => "John",
"lastName" => 'Doe'
)
$id = $db->insert('users', $data)
$id = $db->insert('users', $data);
if($id)
echo 'user was created. Id='.$id;
```
......@@ -28,6 +28,7 @@ Insert with functions use
```php
$data = Array(
'login' => 'admin',
'active' => true,
'firstName' => 'John',
'lastName' => 'Doe',
'password' => $db->func('SHA1(?)',Array ("secretpassword+salt")),
......@@ -39,7 +40,7 @@ $data = Array(
// 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;
```
......@@ -51,8 +52,8 @@ $data = Array (
'lastName' => 'Tables',
'editCount' => $db->inc(2),
// editCount = editCount + 2;
'editBoolean' => $db->not()
// editBoolean = !editBoolean;
'active' => $db->not()
// active = !active;
);
$db->where('id', 1);
if($db->update('users', $data)) echo 'successfully updated';
......@@ -91,7 +92,7 @@ echo $user['id'];
### Delete Query
```php
$db->where('id', 1);
if($db->delete('posts')) echo 'successfully deleted';
if($db->delete('users')) echo 'successfully deleted';
```
### Generic Query Method
......@@ -126,7 +127,6 @@ $results = $db->get('users');
// Gives: SELECT * FROM users WHERE id=1 AND login='admin';
```
Custom Operators:
```php
$db->where('id', Array('>=' => 50));
$results = $db->get('users');
......@@ -136,6 +136,7 @@ $results = $db->get('users');
BETWEEN:
```php
$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
```
......@@ -143,6 +144,7 @@ $results = $db->get('users');
IN:
```php
$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');
```
......@@ -162,12 +164,26 @@ $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');
```
......@@ -194,3 +210,15 @@ $db->where("u.id", 6);
$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();
```
......@@ -8,6 +8,7 @@ if(!$db) die("Database error");
$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)',
......@@ -15,9 +16,15 @@ $tables = Array (
'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',
......@@ -37,6 +44,7 @@ $data = Array (
'loginCount' => $db->inc(2)
),
Array ('login' => 'user3',
'active' => true,
'customerId' => 11,
'firstName' => 'Pete',
'lastName' => 'D',
......@@ -45,7 +53,30 @@ $data = Array (
'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) {
......@@ -64,13 +95,16 @@ foreach ($tables as $name => $fields) {
createTable ($name, $fields);
}
foreach ($data as $d) {
$id = $db->insert("users", $d);
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");
......@@ -79,6 +113,23 @@ 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");
......@@ -147,12 +198,29 @@ if ($db->count != 1) {
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