Last active
August 29, 2015 14:24
-
-
Save manpages/123630e8cbd8c5aae27c to your computer and use it in GitHub Desktop.
Monadic MySQLi, take I
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
include_once('./lib/utils.php'); | |
function rtn() { | |
$xs = func_get_args(); | |
$y = call_user_func_array('mysqli_prepare', $xs); | |
if ($y === false) | |
die(nok( 'MySQL Error: ' . hesc(mysqli_error($xs[0])) )); | |
return $y; | |
} | |
function bind() { | |
$xs = func_get_args(); | |
$y = call_user_func_array('mysqli_stmt_bind_param', v2r($xs)); | |
if ($y === false) | |
die(nok( 'MySQL Error while binding:' . "\n" . hfr($xs) )); | |
return $y; | |
} | |
function run($a) { | |
$xs = func_get_args(); | |
$statement = $xs[0]; | |
$y = call_user_func_array('mysqli_stmt_execute', $xs); | |
if ($y === false) | |
die(nok( 'MySQL Error while binding:' . "\n" . hfr($xs) )); | |
$s = $statement->get_result(); // Mutability, wooo~ | |
if ($s === false) | |
return handleEither($statement); | |
$data = Array(); | |
while ($row = $s->fetch_array(MYSQLI_ASSOC)) { | |
array_push($data, $row); | |
} | |
return $data; | |
} | |
function chain() { | |
$xs = func_get_args(); | |
$db = array_shift($xs); | |
$q = array_shift($xs); | |
$rest = $xs; | |
// | |
$m = rtn($db, $q); | |
$xs1 = Array($m); | |
$xs1 = array_merge($xs1, $rest); | |
// | |
call_user_func_array('bind', $xs1); | |
return run($m); | |
} | |
function v2r($arr) { // Kittens are sad. | |
if (strnatcmp(phpversion(),'5.3') >= 0) { | |
$refs = array(); | |
foreach($arr as $key => $value) | |
$refs[$key] = &$arr[$key]; | |
return $refs; | |
} | |
return $arr; | |
} | |
function handleEither($x) { | |
if ($x->errno !== 0) | |
die(nok('Execution failure (' . $x->errno . '): ' . $x->error)); | |
else | |
return Array(); | |
} | |
function sqlInArray($db, $xs) { | |
$ys = Array(); | |
foreach ($xs as $x) { | |
$ys []= mysqli_real_escape_string($db, $x); | |
} | |
return '("' . implode('", "', $ys) . '")'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment