Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //POST: {"name":"pgsql_function_name","param":{"PARAM1":"VALUE1","PARAM2":"VALUE2"}}
- <?php
- try {
- $input = json_decode(file_get_contents('php://input'), true);
- $func = $input["name"] . "(" . implode(",", array_fill(0, count($input["param"]), "?")) . ")";
- $conn = new PDO("pgsql:host=localhost;port=5432;dbname=testdb;user=myuser;password=mypass");
- $conn->beginTransaction();
- $stmt = $conn->prepare("SELECT " . $func);
- $i = 1;
- foreach ($input["param"] as &$param) {
- $stmt->bindParam($i++, $param, PDO::PARAM_STR);
- }
- if (!$stmt->execute()) {
- $error_info = $stmt->errorInfo();
- echo "Error: SQLSTATE " . $error_info[0] . PHP_EOL;
- echo "DB error code: " . $error_info[1] . PHP_EOL;
- echo "DB error message: " . $error_info[2] . PHP_EOL;
- http_response_code(500);
- exit();
- }
- $cursors = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
- $stmt = null;
- $results = array();
- foreach ($cursors as $index => $value) {
- $stmt = $conn->query('FETCH ALL IN "' . reset($value) . '"');
- $table = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
- $stmt = null;
- foreach ($table as &$row) {
- foreach ($row as &$col) {
- if (is_null($col)) {$col = "";}
- }
- }
- $results[$index] = $table;
- }
- $conn->commit();
- $conn = null;
- echo json_encode(count($results) == 1 ? $results[0] : $results);
- } catch (Exception $e) {
- echo "Exception: " . $e->getMessage();
- http_response_code(500);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement