【问题标题】:How to check if id already exists in mysql with php如何使用php检查mysql中是否已经存在id
【发布时间】:2016-06-26 15:54:41
【问题描述】:

我想先检查一下 mycode_sn 是否存在于数据库中。 如果 mycode_sn 不存在,什么也不做。

这是函数:

function input_me_by_mycode($input_type, $input_id, $total_number)
    {
        if ($input_type == 'mycode') {
            $my_info = $this->db->get_where('mytable', array(
                'mycode_sn' => $input_id
            ))->row();

            }

                echo '<tr id="entry_row_' . $total_number . '">;

    }

我尝试了多种方法,但显然我不太了解。

现在在不存在的情况下,我会收到消息:

遇到 PHP 错误 严重性:通知消息:正在尝试获取 非对象的属性

【问题讨论】:

    标签: php mysql codeigniter activerecord mysqli


    【解决方案1】:

    使用活动记录num_rows()检查记录

    public function input_me_by_mycode($input_type, $input_id, $total_number)
    {
        if ($input_type == 'mycode') {
             $this->db->where('mycode_sn',$input_id);
             $query = $this->db->get('mytable');
             $result = $query->row();
    
           if ($query->num_rows() > 0)
                echo "ID Exist. ID is : ".$result->mycode_sn;
            } else {
                echo "ID doesn't Exist.";
            }
    
        } 
        else {
            echo "Input Type is not equesl to 'mycode' ";
        }   
    }
    

    【讨论】:

      【解决方案2】:

      试试这个

      public function input_me_by_mycode($input_type, $input_id, $total_number)
      {
          if ($input_type == 'mycode') {
              $query = $this->db->query("SELECT * FROM mytable WHERE mycode_sn = '$input_id' ");
              $result = $query->result_array();
      
              if (!empty($result)) {
                  echo "ID Exist. ID is : ".$result[0]['mycode_sn'];
              } else {
                  echo "ID doesn't Exist.";
              }
      
          } 
          else {
              echo "Input Type is not equesl to 'mycode' ";
          }   
      }
      

      【讨论】:

      • @Alex 乐于助人
      • @YourCommonSense 在控制器中,这将通过$this-&gt;input-&gt;post('input_id'); 获得。所以没有问题
      • 你刚才说的和sql注入无关,不保护任何东西。
      • @YourCommonSense 我的小项目已经完全关闭,只能在本地网络上使用。这次安全并不重要。无论如何,谢谢你们俩的讨论。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-04
      • 2014-08-07
      • 2012-11-27
      • 1970-01-01
      • 1970-01-01
      • 2015-03-10
      相关资源
      最近更新 更多