【问题标题】:How can I split a string by ; and store in mysql using php如何拆分字符串;并使用php存储在mysql中
【发布时间】:2018-01-25 16:50:10
【问题描述】:

我有两张桌子

tbl_patient 
pid       sample_id    fullname             test_ivd
 1        AA01         John Vick            test 1; test 2; test 3

tbl_test
tid         sample_id    name_test
 1          AA01         test 1
 2          AA01         test 2
 3          AA01         test 3     

当我将一条新记录(新患者)添加到 tbl_patient 中时,我存储了一个由 ; 分隔的字符串(测试名称列表)在 test_ivd 字段中。同时,我想将 test_ivd 拆分为 ;并添加到 tbl_test 中的 3 条新记录。所以请给我一些建议。

感谢您的任何建议。

【问题讨论】:

  • 为什么要以这种冗余方式存储数据?如果更新一个成功而另一个失败,那只会增加出错的可能性......您应该在需要时使用适当的 JOIN 从 tbl_test 表中获取这些数据。
  • @user2486 这个问题有什么关系?他不需要交替分隔符。

标签: php mysql split


【解决方案1】:

使用explode:explode (string $delimiter, string $string [, int $limit = PHP_INT_MAX]) http://php.net/manual/es/function.explode.php

【讨论】:

    【解决方案2】:

    您可以使用PHP explode 函数来执行此操作。

    $ivdString = 'test 1; test 2; test 3';
    $strArr = explode(";", $ivdString);
    

    用于插入记录。

    foreach ($strArr as $key => $value) {
          $sql = INSERT into table(sample_id,name_test)values('', '$value');
          Your insert here ...
          ......
    }
    

    【讨论】:

      【解决方案3】:

      例子:

      $string = "chicken;lamb;beef";
      $stuff = explode(";", $string);
      print_r($stuff);
      
      //access by $stuff[0], $stuff[1] etc
      

      【讨论】:

        【解决方案4】:

        我建议用 php 处理。

        1. 将患者插入数据库
        2. 检索插入的 id
        3. 将测试插入测试表以获取检索到的 id(您可以编写查询以插入患者的 sample_id 而不是其 id)

        【讨论】:

          猜你喜欢
          • 2015-12-27
          • 1970-01-01
          • 1970-01-01
          • 2015-08-24
          • 1970-01-01
          • 2012-12-01
          • 2017-03-07
          • 1970-01-01
          相关资源
          最近更新 更多