Facebook
From ekstenshun, 1 Month ago, written in PHP.
Embed
Download Paste or View Raw
Hits: 109
  1. function runQuery($conn, $query, $values = [])
  2. {
  3.   $stmt = $conn->prepare($query);
  4.   if (!$stmt) {
  5.     die("Statement preparation failed: $conn->error");
  6.   }
  7.  
  8.   if (!empty($values)) {
  9.     $types = "";
  10.     foreach ($values as $value) {
  11.       if (is_int($value)) {
  12.         $types .= "i";
  13.       } elseif (is_float($value)) {
  14.         $types .= "d";
  15.       } elseif (is_string($value)) {
  16.         $types .= "s";
  17.       } else {
  18.         $types .= "b";
  19.       }
  20.     }
  21.     $stmt->bind_param($types, ...$values);
  22.   }
  23.  
  24.   if (!$stmt->execute()) {
  25.     die("Statement execution failed: " . $stmt->error);
  26.   }
  27.  
  28.   $result = $stmt->get_result();
  29.   if ($result === false) {
  30.     return ['rows' => 0, 'data' => []];
  31.   }
  32.  
  33.   $data = [];
  34.   while ($row = $result->fetch_assoc()) {
  35.     $data[] = $row;
  36.   }
  37.  
  38.   $num_rows = count($data);
  39.  
  40.   $stmt->close();
  41.  
  42.   return ['rows' => $num_rows, 'data' => $data];
  43. }
  44. //usage:
  45. runQuery($conn, "SELECT name FROM people WHERE id = ?;", [2]);