Сбой SQL-запроса без сообщения об ошибке

0

Я использую CodeIgniter 3, и я пытаюсь изменить SQL-запрос из

SELECT id, контрольная отметка из документов, где collection_id = 'ubb'

в

SELECT document_id, отметка времени из documents_revisions, где collection_id = 'ubb' и last = '1'

Первый SQL-запрос генерируется с помощью:

 public function getDocumentsForCollection($sCollectionId) {
    $this->db->select('id, shelfmark');
    $this->db->where('collection_id', $sCollectionId);
    $query = $this->db->get('documents');
    if($query->num_rows() > 0) {
      return $query->result();
    }
    else {
      return '';
    }
  }    

Чтобы сопоставить второй SQL-запрос, я обновил этот метод до

  public function getDocumentsForCollection($sCollectionId) {
    $this->db->select('document_id, shelfmark');
    $where = "collection_id=" . $sCollectionId . " AND latest=1";
    $this->db->where($where);
    $query = $this->db->get('documents_revisions');
    if($query->num_rows() > 0) {
      return $query->result();
    }
    else {
      return '';
    }
  }

Когда я открываю страницу, где выполняется функция, я просто вижу пустую страницу.

Как я могу отлаживать в CodeIgniter, чтобы увидеть сгенерированный SQL-запрос моей функции PHP?

Что случилось с моей обновленной функцией PHP?


Я обновил метод до:

  public function getDocumentsForCollection($sCollectionId) {
    $this->db->select('document_id, shelfmark');
    $where = array("collection_id"=>$sCollectionId,"latest"=>1);
    $this->db->where($where);
    $query = $this->db->get('documents_revisions');
    var_dump($query); exit;
    if($query->num_rows() > 0) {
      return $query->result();
    }
    else {
      return 'foo';
    }
  }

С var_dump ($ query) прямо перед условием if я получаю:

объект (CI_DB_mysqli_result) # 65 (8) {["conn_id"] => object (mysqli) # 16 (19) {["affected_rows"] => int (160) ["client_info"] => string (79) " mysqlnd 5.0.12-dev - 20150407 - $ Id: b5c5906d452ec590732a93b051f3827e02749b83 $ "[" client_version "] => int (50012) [" connect_errno "] => int (0) [" connect_error "] => NULL [" errno "] => int (0) ["error"] => string (0) "" ["error_list"] => array (0) {} ["field_count"] => int (2) ["host_info"] => string (25) "Localhost через UNIX-сокет" ["info"] => NULL ["insert_id"] => int (0) ["server_info"] => string (23) "5.7.18-0ubuntu0.16.04.1 "[" server_version "] => int (50718) [" stat "] => string (139)" Время работы: 252001 Темы: 3 Вопросы: 36434 Медленные запросы: 0 Открывает: 501 Таблицы Flush: 1 Открытые таблицы: 313 Запросов за второй avg: 0.144 "[" sqlstate "] => string (5)" 00000 "[" protocol_version "] => int (10) [" thread_id "] => int (2507) [" warning_count "] => int ( 0)} ["result_id"] => object (mysqli_result) # 38 (5) {["current_field"] => int (0) ["field_count"] => int (2) ["lengths"] => NULL ["num_rows"] => int (160) [ "type"] => int (0)} ["result_array"] => array (0) {} ["result_object"] => array (0) {} ["custom_result_object"] => array (0) {} ["current_row"] => int (0) ["num_rows"] => NULL ["row_data"] => NULL}

Вследствие этого action_rows представляет количество документов, которые я получаю, если я запускаю SQL-запрос непосредственно в MySQL: ["affected_rows"] => int (160)

Теги:
codeigniter

1 ответ

1

Вы должны передать массив в случае нескольких условий в db-> where()

$where = array("collection_id"=>$sCollectionId,"latest"=>1);

ПОЛНЫЙ КОД:

public function getDocumentsForCollection($sCollectionId) {
$this->db->select('document_id, shelfmark');
$where = array("collection_id"=>$sCollectionId,"latest"=>1);
$this->db->where($where);
$query = $this->db->get('documents_revisions');
if($query->num_rows() > 0) {
  return $query->result();
}
else {
  return 'foo';
}

}

будет генерировать результат следующим образом:

SELECT 'document_id', 'shelfmark' FROM ('documents_revisions') WHERE 'collection_id' = 'ubb' AND 'latest' = 1

Руководство по использованию Where Where: https://www.codeigniter.com/userguide3/database/query_builder.html#looking-for-specific-data

  • 0
    Я получаю сообщение «Произошла ошибка PHP - Серьезность: Уведомление - Сообщение: неопределенное свойство: stdClass :: $ id»
  • 0
    Не просто массив, так как вы можете звонить where несколько раз, как сказано в комментариях к вопросу.
Показать ещё 2 комментария

Ещё вопросы

Сообщество Overcoder
Наверх
Меню