Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- interface SomeOtherSQL{
- const HelloWorld = [
- "SELECT 'hello' as 'world';"
- ];
- }
- interface Example extends SomeOtherSQL{
- const EchoExample = [
- 'in'=>[
- 'pin'=>'VARCHAR(50)'
- ],
- "SELECT {0} as 'input';"
- ];
- const AddExample = [
- 'in'=>[
- 'pa'=>'VARCHAR(50)',
- 'pb'=>'VARCHAR(50)'
- ],
- "SELECT {0}+{1} as 'added';"
- ];
- }
- class sql_base{
- static function __callStatic($command,$params){
- $marks = str_pad("",count($params)*2-1,"?,");
- $host = static::$host;
- $username = static::$username;
- $database = static::$database;
- $port = static::$port;
- $password = static::$password;
- $dsn = "mysql:host=$host;port=$port;dbname=$database";
- $db = new PDO($dsn, $username, $password);
- $query = $db->prepare("SHOW PROCEDURE STATUS where `Name`=? AND `Db`='$database'");
- $query->execute(array($command));
- $procExists = $query->fetch(PDO::FETCH_ASSOC,PDO::FETCH_ORI_NEXT);
- if(!$procExists)
- {
- $class = get_called_class();
- if(defined("$class::$command")){
- $code = constant("$class::$command");
- $sql = "";
- $i=-1;
- while(isset($code[++$i])){
- $sql.=$code[$i]."\n";
- }
- $type = isset($code['type'])?$code['type']:"procedure";
- $newParams = [];
- foreach(['in','out'] as $d){
- if(isset($code[$d]))foreach($code[$d] as $p=>$n){
- $newParams[] = $type=="procedure"?"$d `$p` $n":"`$p` $n";
- }
- }
- if(isset($code['in'])){
- $paramKeys = array_keys($code['in']);
- $sql = preg_replace_callback("/\\{([0-9]+)\\}/",function($matches) use (&$paramKeys){
- return '`'.$paramKeys[$matches[1]].'`';
- },$sql);
- }
- $newParams = implode(", ",$newParams);
- $procSql = "CREATE $type $command($newParams) \n BEGIN $sql \n END";
- $query = $db->prepare($procSql);
- if(!$query)
- throw new Exception(json_encode($db->errorInfo()));
- else if(!$query->execute())
- throw new Exception(json_encode(array("errorinfo"=>$query->errorInfo(),"parameters"=>$newParams,"sqlcode"=>$code)));
- }
- else throw new Exception("Missing sql procedure '$command'");
- }
- $query = $db->prepare("CALL $command($marks)");
- if(!$query)
- throw new Exception(json_encode($db->errorInfo()));
- else{
- if(!$query->execute($params)) throw new Exception(json_encode(array($query->errorInfo(),$params)));
- else{
- $return = $query->fetchAll(PDO::FETCH_ASSOC);
- if(count($return)==0)return $db->lastInsertId();
- return $return;
- }
- }
- }
- }
- class sql extends sql_base implements Example{ // fill out fields
- protected static $host = "";
- protected static $username = "";
- protected static $database = "";
- protected static $port = "";
- protected static $password = "";
- }
- print_r(sql::HelloWorld());
- echo "<br>";
- print_r(sql::AddExample(3,4));
- echo "<br>";
- print_r(sql::EchoExample("uwotm8"));
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement