php - 在类中嵌套 PHP SQL 查询

标签 php mysql

我是 PHP 新手,所以请耐心等待。

我正在编写一个 PHP 片段来从 MySQL 数据库中检索复杂的数据结构。 (想想“有一个”对象关系。)我有一个将结果转换为 PHP 对象列表的 SQL 查询。这些 PHP 对象包含在其他 MySQL 表中定义的 PHP 对象(有时以数组的形式)。因此,第一个对象的构造函数必须在构造时执行自己的 SQL 查询以构建内部对象。不幸的是,我不习惯这样做,所以我不断收到这个错误:

Database error: SQLSTATE[HY093]: Invalid parameter number: parameter was not defined

我该如何设置它,以便在我调用 get_tickets.php 时,它不会出现这些 SQL 查询问题?

配置.php

<?php
  // These variables define the connection information for your MySQL database
  $dbhost = '####';
  $dbuser = '####';
  $dbpass = '####';
  $dbname = '####';

  $options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');

  // Attempt to connect to the database
  try {
    $db = new PDO("mysql:host={$dbhost};dbname={$dbname};charset=utf8",
                     $dbuser, $dbpass, $options);
  } catch (PDOException $ex) {
     die("Failed to connect to the database: " . $ex->getMessage());
  }

  $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  $db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

  // Disable magic quotes
  if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc())
  {
      function undo_magic_quotes_gpc(&$array)
      {
          foreach($array as &$value)
          {
              if(is_array($value))
              {
                undo_magic_quotes_gpc($value);
              }
              else
              {
                  $value = stripslashes($value);
              }
          }
      }
      undo_magic_quotes_gpc($_POST);
      undo_magic_quotes_gpc($_GET);
      undo_magic_quotes_gpc($_COOKIE);
  }

  // Tell browser to use UTF-8 encoding
  header('Content-Type: text/html; charset=utf-8');

  // Start the session
  if(!isset($_SESSION)){
      session_start();
  }  
?>

get_tickets.php

<?php
  require_once('config.php');
  require('data_access_objects.php');

  // Check for hash
  if (isset($_POST['hash'])) { 
    // Get user's hash
    $hash = $_POST['hash'];

    // Result array to return
    $results = Array();

    try {
      // Get all ticket entries
      $query = "SELECT *
                  FROM tickets 
                  WHERE user = (
                    SELECT id 
                    FROM users 
                    WHERE hash = :hash)";
      $stmt = $db->prepare($query);
      $stmt->bindValue(':hash', $hash, PDO::PARAM_STR);
      $stmt->execute();

      // Convert cursor entries into class objects
      while($row = $stmt->fetch()) {
        array_push($results, new Ticket($row['id'], $row['status'], $row['room'], 
                     $row['location'], $row['gps_loc'], $row['subject'],
                     $row['picture'], NULL));
      }

      // Display resulting array entries
      echo json_encode(array_values($results));
    } catch (PDOException $ex) {
      // Display generic error on page
      echo 'Database error: ' . $ex->getMessage();
    }
  } else {
    // Failed, return nothing
    echo '';
  }
?>

data_access_objects.php

<?php
  /* Room data access object structure */
  class Room
  {
    var $id;
    var $name;
    var $building;

    function __construct($id, $name, $building)
    {
      $this->id = $id;
      $this->name = $name;
      $this->building = $building;
    }
}

/* Ticket data access object structure */
class Ticket
{
    var $id;
    ...
    var $room;
    ...
    var $messages = Array();

    function __construct($id, $status, $room, $location, $gpsLocation, 
                           $subject, $picture, $messages)
    {
      $this->id = $id;
      ...
      $this->retrieveRoom($room);
      ...
      $this->messages = $messages;
    }

    private function retrieveRoom($room_id)
    {
      require_once('config.php');
      try {
        // Get all ticket entries
        $query = "SELECT *
                    FROM rooms 
                    WHERE id = :room_id)";
        $stmt = $db->prepare($query);
        $stmt->bindValue(':id', $room_id, PDO::PARAM_INT);
        $stmt->execute();

        // Convert cursor entrie into room object
        $row = $stmt->fetch();
        $this->room = new Room($row['id'], $row['name'], $row['building']);
      } catch (PDOException $ex) {
        // Display generic error on page
        echo 'Database error: ' . $ex->getMessage();
      }''
    }
    ...
  }
?>

最佳答案

看起来 PDO 正在提示无效参数,我会检查到底是什么绑定(bind)到您的方法:

private function retrieveRoom($room_id)

为了保护起见,在发出查询之前限定 $room_id 是数字。

虽然您当前的方法效率低下,但我会补充。您应该压缩查询并根据连接的记录创建对象。

关于php - 在类中嵌套 PHP SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34216636/

相关文章:

php - Android 应用程序与用代码点火器框架编写的 php 文件通信

php - 在从其他网址获取图像时将图像转换为 base64

php - 在 Woocommerce 中显示客户订单评论(客户备注)

php - 使用php脚本在Android应用程序中上传图像

mySQL 大文本比较性能...最佳实践?

运行 mysql 命令大文件时 MySQL 消失错误

php - MySQL数据建模

MySql - 如何仅返回字段的一部分 - 如果字段中存在某个单词,则删除该单词

MYSQL查询: SELECT DISTINCT IMEI from query

MySQL 触发器、 View 、单独的表或忠诚度积分的即时计算?