如何在mysql中存储数组的值?

时间:2017-03-07 15:36:36

标签: php mysql arrays database codeigniter

是否可以将数据库中的值作为数组检索并将相同的值保存回数据库?

例如,在我的table1中,它返回一个数组:

array(1) { 
   [0]=> string(5) "test1" 
}

我想将 test1 保存回我的数据库。

代码:

查看

  <?php //for viewing data
  foreach ($users as $user) {
     echo $user->empID;
     echo '<br>';
  }
   ?>
   <?php //for inserting data
  foreach ($users as $row) {
     $rec_users[] = $row->empID;
  }
       echo form_multiselect('empRequired[]', $rec_users, $rec_users,  array('class' => 'chosen-select', 'multiple style' => 'width:785px;'));
?>

控制器

    $lid = $this->admin_model->getID();
    foreach ($lid as $id) {
        $last_id = $id['projectID'];
        $data['users'] = $this->admin_model->getUsers($last_id);
    }

    $this->load->view('admin/projects/rec-employee', $data);

$recommended = $this->input->post('empRequired');

foreach ($recommended as $row) {
   $data1 = array(
            'projectID' => $last_id,
            'username' => $row
   );

   $this->admin_model->insertRecEmp($data1);
}

模型

    public function insertRecEmp($data){
        return $this->db->insert('projectemp', $data);
    }


Table 1: primary key
+--------+
|username|
+--------+
| test1  |
+--------+

Table 2: foreign key

+--------+----------+
|empID   |projectID |
+--------+----------+
| test1  |          |
+--------+----------+

enter image description here

我希望下拉列表中的test1保存在我的数据库中,但是当我点击下一步时,它会导致

enter image description here

而不是test1,它返回0。

3 个答案:

答案 0 :(得分:0)

序列化数组并将其存储在dbase中

http://us.php.net/manual/en/function.serialize.php

答案 1 :(得分:0)

<?php 
// $session_data contains a multi-dimensional array with session
// information for the current user. We use serialize() to store 
// it in a database at the end of the request. 
$conn = odbc_connect("webdb", "php", "chicken"); 
$stmt = odbc_prepare($conn, "UPDATE sessions SET data = ? WHERE id = ?");
$sqldata = array (serialize($session_data), $_SERVER['PHP_AUTH_USER']); 
if (!odbc_execute($stmt, $sqldata)) { 
$stmt = odbc_prepare($conn, "INSERT INTO sessions (id, data) VALUES(?,?)"); 
if (!odbc_execute($stmt, $sqldata)) { 
/* Something went wrong.. */ } 
} 

?&gt;

注意:如果您想从数据库获取此数据,请使用unserializ(),它可以帮助您将字符串转换为数组

答案 2 :(得分:0)

你的foreach在每次传递时都会覆盖$ data1数组,控制器应该是这样的:

   foreach ($lid as $id) {
    $last_id = $id['projectID'];
    $data['users'] = $this->admin_model->getUsers($last_id);
}

$this->load->view('admin/projects/rec-employee', $data);

$recommended = $this->input->post('empRequired');

foreach ($recommended as $row) {
   //this line is the changed one
   $data1[] = array(
            'projectID' => $last_id,
            'username' => $row
   );

   $this->admin_model->insertRecEmp($data1);
}