将每个数组值作为codeigniter中的单独行从控制器插入到模型

时间:2017-02-03 05:26:41

标签: php mysql ajax codeigniter

我动态获取数组值但是我无法将数组值作为单独的行添加到codeigniter中的MySQL数据库中。

Ajax的输出是A 1000 B 400

控制器

function get_details()
{
  $this->db->trans_start();
  $query = $this->db->query("SELECT * from `appointment_details` ORDER BY `appointment_id` DESC");
  $this->db->trans_complete();
  if($query->num_rows()>=1)
    return $query->result()[0]->appointment_id;
}

function patient_investigation_details($myTableArray,$appointment_id)
{
  $query_string="INSERT into `patient_investigation_details`(`investigation_name`,`price`,`appointment_id`) VALUES";
  foreach ($myTableArray as $row)
  {
    $query_string.="('".$row['1']."','". $row['2']."','".$appointment_id."')";
  }
  $this->db->trans_start();
  $query = $this->db->query($query_string);
  $this->db->trans_complete();

  if ($this->db->trans_status() === FALSE){
   return null;
  }
  else{
   return TRUE;
  } 
}

模型

var React = require('react');
var ReactDOM = require('react-dom');

var NavBar = React.createClass({

render: function () {

    return (
        <div className="navbar navbar-default">
                    <div className="container">
                        <div className="navbar-header pull-left">
                            <ul className="nav navbar-nav">
                                <li className="active"><a>Home<span className="sr-only">(current)</span></a></li>
                            </ul>
                        </div>
                        <div className="navbar-header pull-right">
                            <ul className="nav navbar-nav navbar-right">
                                <li className="dropdown">
                                    <a id="userAdsId" className="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Welcome, Bibin</a>
                                </li>
                            </ul>
                        </div>
                    </div>
        </div>
    )

}

});

module.exports = NavBar

1 个答案:

答案 0 :(得分:1)

您应该尝试创建一个用于插入的数组,然后批量插入它们。这将迭代foreach循环并创建插入数组

另外,对于获取appointment_id,不需要从表中提取*(全部)。只需通过应用限制1获取最高行

即可从中获取appointment_id
    function get_details()
    {
        $this->db->trans_start();
        $query = $this->db->query("SELECT appointment_id from `appointment_details` ORDER BY `appointment_id` DESC limit 1");
        $this->db->trans_complete();
        if($query->num_rows()>=1)
            return $this->db->get()->row()->appointment_id;
    }

    function patient_investigation_details($myTableArray,$appointment_id)
    {
     foreach ( $myTableArray as $row){
            $data[] = array(
                    'investigation_name' => $row['1'],
                    'price'=> $row['2'],
                    'appointment_id'=>$appointment_id
            );
        }
    $this->db->insert_batch('patient_investigation_details', $data);
    }