Skip to content

Instantly share code, notes, and snippets.

@keiya
Created August 1, 2012 08:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save keiya/3224802 to your computer and use it in GitHub Desktop.
Save keiya/3224802 to your computer and use it in GitHub Desktop.
Database O/RM
<?php
/*
* KDB database wrapper by Keiya Chinen <keiya_21@yahoo.co.jp>
*/
class KDB {
public function __construct ($user,$pass,$db,$host) {
$this->mysqli = new mysqli($host, $user, $pass, $db);
if ($this->mysqli->connect_error) {
error_log('mysqli:(could not connect to database) '.$this->mysqli->connect_error());
die('FATAL');
}
$this->mysqli->set_charset('utf8');
}
// overload
public function __get($table) {
$this->table = $table;
return $this;
}
public function query() {
$res = $this->mysqli->query($this->sql);
if ($res === true) {
}
else if ($res === false) {
error_log('mysqli:(query failed) '.$this->mysqli->error);
return false;
}
else {
$array = array();
while ($row = $res->fetch_assoc()) {
$array[] = $row;
}
return $array;
}
}
public function raw_query($placehold,$args) {
foreach ($args as $k => $v) {
$args[$k] = $this->mysqli->real_escape_string($v);
}
$this->sql = str_replace(
'?',
$args,
$placehold
);
return $this->query();
}
public function update($assoc) {
$this->sql = "UPDATE {$this->table} SET ";
foreach ($assoc as $k => $v) {
$this->sql .= "`{$k}`='".$this->mysqli->real_escape_string($v).'\',';
}
$this->sql = substr($this->sql, 0, -1);
return $this;
}
public function insert($assoc) {
$this->sql = "INSERT INTO {$this->table} SET ";
foreach ($assoc as $k => $v) {
$this->sql .= "`{$k}`='".$this->mysqli->real_escape_string($v).'\',';
}
$this->sql = substr($this->sql, 0, -1);
return $this;
}
}
<?php
/*
* User register with KDB O/RM sample
*/
require_once 'KDB.php';
$key = 'as8uhjnkjasdfb';
// 16 chars
$profile['username'] = $POST_['username'];
// password will be hashed
$profile['password'] = hash_hmac('sha512',$POST_['password'],$key,true);
// Y-m-d form
$profile['birthdate'] = $POST_['birthdate'];
$db = new KDB('root','','sso_cp','localhost');
$db->users->insert($profile)->query();
@keiya
Copy link
Author

keiya commented Aug 1, 2012

KDBっていうデータベースラッパーと、それをつかってユーザ登録をするサンプル。
ユーザ登録でのパスワードは鍵付きSHA512ハッシュ関数(HMAC SHA)によりハッシュ化で、バイナリで格納。

スキーマは以下の通り
id int(10)
username varchar(16)
password binary(64)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment