Advertisement
Guest User

Untitled

a guest
Oct 12th, 2018
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.61 KB | None | 0 0
  1. //POST: {"name":"pgsql_function_name","param":{"PARAM1":"VALUE1","PARAM2":"VALUE2"}}
  2.  
  3. <?php
  4. try {
  5.     $input = json_decode(file_get_contents('php://input'), true);
  6.     $func = $input["name"] . "(" . implode(",", array_fill(0, count($input["param"]), "?")) . ")";
  7.  
  8.     $conn = new PDO("pgsql:host=localhost;port=5432;dbname=testdb;user=myuser;password=mypass");
  9.     $conn->beginTransaction();
  10.  
  11.     $stmt = $conn->prepare("SELECT " . $func);
  12.     $i = 1;
  13.     foreach ($input["param"] as &$param) {
  14.         $stmt->bindParam($i++, $param, PDO::PARAM_STR);
  15.     }
  16.  
  17.     if (!$stmt->execute()) {
  18.         $error_info = $stmt->errorInfo();
  19.         echo "Error: SQLSTATE " . $error_info[0] . PHP_EOL;
  20.         echo "DB error code: " . $error_info[1] . PHP_EOL;
  21.         echo "DB error message: " . $error_info[2] . PHP_EOL;
  22.         http_response_code(500);
  23.         exit();
  24.     }
  25.     $cursors = $stmt->fetchAll(PDO::FETCH_ASSOC);
  26.     $stmt->closeCursor();
  27.     $stmt = null;
  28.  
  29.     $results = array();
  30.     foreach ($cursors as $index => $value) {
  31.         $stmt = $conn->query('FETCH ALL IN "' . reset($value) . '"');
  32.         $table = $stmt->fetchAll(PDO::FETCH_ASSOC);
  33.         $stmt->closeCursor();
  34.         $stmt = null;
  35.  
  36.         foreach ($table as &$row) {
  37.             foreach ($row as &$col) {
  38.                 if (is_null($col)) {$col = "";}
  39.             }
  40.         }
  41.  
  42.         $results[$index] = $table;
  43.     }
  44.  
  45.     $conn->commit();
  46.     $conn = null;
  47.  
  48.     echo json_encode(count($results) == 1 ? $results[0] : $results);
  49. } catch (Exception $e) {
  50.     echo "Exception: " . $e->getMessage();
  51.     http_response_code(500);
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement