Codeigniter将数组插入数据库

3

我在Codeigniter中创建了一个表单,其中包含一个电话号码字段,使用JavaScript动态复制。因此,基本上我可以有一个或多个这样的字段。

<input name="phone[]" value=""type="text">
<input name="phone[]" value=""type="text">

然后在我的控制器中,我有以下代码:
$form_data = array(
    'first_name' => $this->input->post('first_name'),
    'last_name' => $this->input->post('last_name'),
    'phone' => $this->input->post('phone[]')
    );

然后我将其保存到我的数据库中,如下所示:

function SaveForm($form_data)
{
    $this->db->insert('customers', $form_data);
    if ($this->db->affected_rows() == '1')
    {
        return TRUE;
    }
    return FALSE;
}

但是很明显,“phone”的代码是错误的,我只是无法弄清楚如何正确地做到这一点。

6个回答

6

无法将数组保存到数据库中。您可以使用implode()将其转换为字符串,每当需要时再使用explode()将其转换回数组。就像下面这样:

$phone=implode(',',$this->input->post('phone'));
$form_data = array(
        'first_name' => $this->input->post('first_name'),
        'last_name' => $this->input->post('last_name'),
        'phone' => $phone
        );

或者

您可以将其转换为JSON字符串,需要时再将其转换回类似以下的数组:

$phone = json_encode($this->input->post('phone'));

将其转换回数组

$phone = json_decode($phone, TRUE);

4

将您的函数修改如下,它将像魔术般地工作:

function SaveForm($form_data)
    {
        foreach ($form_data as $contact)
        {
            $data[] = array(
                'first_name' => $contact['first_name'],
                'last_name' => $contact['last_name'],
                'phone' => $contact['phone']
                );
        }

        $this->db->insert_batch('customers', $data); 

        if ($this->db->affected_rows() > 0)
        {
            return TRUE;
        }
        return FALSE;
    }

已修改:

是的,您必须编辑传递给SaveForm函数的para数组。 请使用以下代码,忽略上面的代码:

    foreach($_POST['first_name'] as $key=>$fname) 
    {
        $form_data[] = array(
            'first_name' => $_POST['first_name'][$key],
            'last_name' => $_POST['last_name'][$key],
            'phone' => $_POST['phone'][$key],
            );
    }

function SaveForm($form_data)
  {
    $this->db->insert_batch('customers', $data); 

    if ($this->db->affected_rows() > 0)
    {
        return TRUE;
    }

    return FALSE;
  }

不幸的是,这个程序出了问题,数组的每一行都会抛出一个“非法字符串偏移量'first_name'”的错误。通过谷歌搜索,这似乎是PHP 5.4中出现的常见问题。我正在使用5.5.8版本。 - skribe
我已经修改了答案,请使用下面“修改后”的代码替换你的代码! - kbhatta
我明白你的意思……但是使用implode()并不像Vinie建议的那样简单,所以我接受了他的答案。 - skribe

0

若要将数组插入数据库,请在Codeigniter控制器中使用此程序 =>

$inputdata=$this->input->post();

$phone=array($inputdata['phone']);
       
       foreach($phone as $arr)
       {
           $phoneNo=$arr;

           $f=count($phoneNo);
           
           for($i=0;$i<$f;$i++)
           {
              $arre=[
                  'phone'=>$phoneNo[$i],
                     ]; 
                  
              $insertB= $this->user_model->userdata($arre);      
           }
       }

0

在控制器中

$phone = $_POST['phone'];//this will store data as array. Check image 02
$form_data = array(
    'first_name' => $this->input->post('first_name'),
    'last_name' => $this->input->post('last_name'),
    'phone' => $phone,//some times it works with '$phone'
);

在模型中

function SaveForm($form_data)
{
    $this->db->insert('customers', $form_data);
    if ($this->db->affected_rows() == '1')
    {
        return TRUE;
    }
    else
    {
        return FALSE;
    }

}

已测试

图像 01(我的表单)

01

图片 02(提交后)

enter image description here


我缺少什么?我曾尝试过类似的事情,但我的和你的产生了相同的错误。 遇到了PHP错误严重性:注意消息:数组转换为字符串文件名:bfmysqli / bfmysqli_driver.php行号:509 发生数据库错误错误编号:1054'Array'在'field list'中是未知列INSERT INTO customers (first_namelast_namephone) VALUES ('franky','smith',Array) - skribe

0

mysql没有任何数组数据类型。因此,我们无法直接将数组存储到mysql数据库中。 为了做到这一点,我们首先需要使用php serialize()函数将数组转换为字符串,然后将其保存到mysql数据库中。

例如:用于将数组存储在数据库中的php代码

$array = array("foo", "bar", "hello", "world");
$conn=mysql_connect('localhost', 'mysql_user', 'mysql_password');
mysql_select_db("mysql_db",$conn);
$array_string=mysql_escape_string(serialize($array));

从数据库中检索数组
$conn=mysql_connect('localhost', 'mysql_user', 'mysql_password');
 mysql_select_db("mysql_db",$conn);
$q=mysql_query("select column from table",$conn);
while($rs=mysql_fetch_assoc($q))
{
 $array= unserialize($rs['column']);
 print_r($array);
}

谢谢您的回答,但正如Bugfixer指出的那样,您的答案并没有使用Codeinigiter,而我遇到问题的地方就在这里。我已经可以在普通的PHP中完成它。 - skribe

-1
public function add_theme_pages(){
        $page_name = $this->input->post('page');
        $page_img = $this->input->post('page_img');

        for($i=0; $i < count($page_name); $i++){

            $pages_data = array(
                    'theme_id' => $this->input->post('theme_id'),
                    'theme_page_name' => $page_name[$i],
                    'theme_page_img' => $page_img[$i]
            );

            if($this->backendM->add_theme_pages($pages_data)){
                $this->session->set_flashdata('message', 'Theme Added Successfully !');
                $this->session->set_flashdata('message_class', 'green');
                $this->create_template();
            }else{
                $this->create_template();
            }
        }   

    }

3
虽然你的代码可能提供了问题的答案,请添加一些上下文,以便其他人了解它的作用和存在意义。 - Theo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接