0

当我向此页面发送包含 POST-DATA ({"bot_hw_id":"2147483647"}) 的请求时,我收到以下错误:

<p>Severity: Notice</p>
<p>Message:  Undefined offset: 0</p>
<p>Filename: models/prometheus_model.php</p>
<p>Line Number: 26</p>

我的代码:

Controller(update_bot function):
[code]public function update_bot()
 {
  $bot_data = json_decode($this->input->post('bot_data'));
  $to_update = array(
  'bot_last_update' => time(),
  'bot_ip' => $_SERVER['REMOTE_ADDR'],
  'bot_port' => $_SERVER['REMOTE_PORT']
  );
  $bot_data = $this->prometheus_model->get_bot_data_by_hw_id(/*$bot_data->{'bot_hw_id'}*/$bot_data->{'bot_hw_id'});
  //echo $bot_data['bot_id'];
  print_r($bot_data);
  $this->prometheus_model->update('bots', array('bot_id' => $bot_data['bot_id']), $to_update);
  //var_dump($bot_data);


 }

模型(prometheus_model):

<?php
class Prometheus_model extends CI_Model {

 var $tables = array(
  'bots' => 'bots'
 );

 function __construct() {
  parent::__construct();
 }

 public function tablename($table = NULL) {
  if(! isset($table)) return FALSE;
  return $this->tables[$table];
 }

 public function get($table, $where = array(), $single = FALSE, $order = NULL) {
  $this->db->where($where);
  if(isset($order)) {
   $this->db->order_by($order);
  }
  $q = $this->db->get_where($this->tablename($table),$where);

  $result = $q->result_array();
  if($single) {
   return $result[0];
  }
  return $result;
 }

 public function update($table, $where = array(), $data) {
  $this->db->update($this->tablename($table),$data,$where);
  return $this->db->affected_rows();
 }

 public function insert($table, $data) {
  $this->db->insert($this->tablename($table),$data);
  return $this->db->insert_id();
 }

 public function delete($table, $where = array()) {
  $this->db->delete($this->tablename($table),$where);
  return $this->db->affected_rows();
 }

 public function explicit($query) {
  $q = $this->db->query($query);
  if(is_object($q)) {
   return $q->result_array();
  } else {
   return $q;
  }
 }

 public function num_rows($table, $where = NULL) {
  if(isset($where)){
  $this->db->where($where);
  }
  $q = $this->db->get($table);
  return $q->num_rows();
 }

 public function get_bot_data_by_hw_id($bot_hw_id) {
  $q = $this->get('bots', array('bot_hw_id' => $bot_hw_id), TRUE);
  return $q;
 }

}

?>;

我该如何解决这个错误?

4

1 回答 1

1

首先,我应该提到,在没有任何过程的情况下完全查询用户输入并不是一个绝对好的和安全的想法(正如我们在您的代码中看到的那样)。至少每个表最好有不同的模型。

反正...

这样您的功能将得到纠正:

 public function get($table, $where = array(), $single = FALSE, $order = NULL) {
  $this->db->where($where);
  if(isset($order)) {
   $this->db->order_by($order);
  }
  $q = $this->db->get_where($this->tablename($table),$where);

  $result = $q->result_array();
  // You should use $q->num_rows() to detect the number of returned rows
  if($q->num_rows() == 1) {
   // Return the first row:
   return $result[0];
  }
  return $result;
 }

只有一个时返回第一行,$q->num_rows()不等于时返回一个数组1

希望能帮助到你

于 2013-06-22T16:53:50.567 回答