php - 内爆数组并将动态数据插入mysql数据库

标签 php mysql

这是向mysql数据库插入动态数据的代码。

    $name = $_POST['name'];
    for ($i = 0; $i < count($name); $i++) {
            if ($name[$i] != "") {
                $test= implode(", ", (array)$name[$i]);                    
                print_r($test);
 $sql = "INSERT INTO employee_table (name)
                     VALUES ('$test')";
            if ($conn->query($sql) === true) {
                echo ('ok');
            }              
                }
        }
        $conn->close(); 

我使用 implode(", ", (array)$name[$i]) 通过逗号从 $name 返回一个字符串,但是当 print_r ($test); 像这样:

AlexBrownHelloHugo

我有两个问题,希望得到你的帮助:

  • print_r($test);Alex,Brown,Hello,Hugo 时的结果
  • $test [Alex,Brown,Hello,Hugo] 同一行存入数据库。

谢谢大家。

最佳答案

像这样:

$names = empty($_POST['name']) ? [] : $_POST['name'];

foreach($names AS $name){
    if (!empty($name)) {
          $test= '['.implode(", ", (array)$name).']';                    
          print_r($test);
          $sql = "INSERT INTO employee_table (name)
                 VALUES ('$test')";
          if ($conn->query($sql) === true) {
            echo ('ok');
         }              
    }
}

我想转发我发表的这条评论:

its a bad idea to store data as a delimited list when you can make it a related table. In any case I would save it as this ,Alex,Brown,Hello,Hugo, with leading and trailing delimiters, that way when you query it you can do this field LIKE '%,Alex,%'. The difference is if you have foo,some,bar and foo,something,bar and you do field LIKE '%some%' note no , you will find both of those some and something. To query the first and last items like I showed above with , they would need the , around them. You can just use trim($field, ',') to remove them before explode etc

更新

还有这个

its unclear the structure of $name is it implode($name[$i]) or impode($name) You use the first one in your code which implies name is [['foo','bar'], [...]] not ['foo','bar', ...] If it's the second your also storing it multiple times which you probably don't want.

所以你可以这样做:

//$_POST['name'] = ['foo','bar', ...]

//remove the loop

 //we can assign $name in the if condition and save a line or 2
 //the second part, the assignment, will always return true.
if (!empty($_POST['name']) && $name = $_POST['name']) {
      $test= '['.implode(',', (array)$name).']';   //changed mainly this line                 
      print_r($test);
      $sql = "INSERT INTO employee_table (name) VALUES ('$test')";
      if ($conn->query($sql) === true) {
         echo 'ok';
      }              
}

没有循环,因为当你遍历名称的计数时,你每次插入相同的数据,直到名称变量中的项目数。

解释你的代码

因此,使用我的示例数据 $_POST['name'] = ['foo','bar', ...] 和原始代码的简化版本,您可以这样做:

假设您在原始代码中的意思是 implode($name) 而不是 implode($name[$i]),这是唯一理智的事情如果您的数据看起来像我的示例数据

 //canned example data
$name = ['foo','bar'];

for ($i = 0; $i < count($name); $i++) {
    if ($name[$i] != "") {
        $test= implode(", ", (array)$name);  //changed from $name[$i] 

        //just output this stuff so we can see the results                 
        print_r($test);
        echo "\nINSERT INTO employee_table (name) VALUES ('$test')\n";
    }
}

输出:

foo, bar
INSERT INTO employee_table (name) VALUES ('foo, bar')
foo, bar
INSERT INTO employee_table (name) VALUES ('foo, bar')

Sandbox

If 应该是显而易见的,但如果您将此行 $test= implode(", ", (array)$name); 更改为 $test= '['.implode(' ,', (array)$name).']; 在上面的代码中,输出将是这样的:

foo, bar
INSERT INTO employee_table (name) VALUES ('[foo,bar]')
foo, bar
INSERT INTO employee_table (name) VALUES ('[foo,bar]')

这仍然保存了不止一次。所以我们需要转储该循环,这基本上迫使我们进入我放在本次更新顶部的代码。

希望一切都有意义。

干杯

关于php - 内爆数组并将动态数据插入mysql数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54957066/

相关文章:

PHP:更新日期值?

php - 在 Mac OS X 10.7.3(默认 php)下安装和启用 APC 缓存

PHP zend left join 转换查询中的日期

php - 使用 SELECT DISTINCT COUNT 在数据库中获取错误的数量

php - 合并sql表中重叠的日期间隔

mysql 计数上限(*)

PHP 锁定不起作用。不明白为什么

PHP-将密码与root密码进行比较

php - 操作 'like' 的排序规则 (utf8mb4_unicode_ci,IMPLICIT) 和 (utf8_general_ci,COERCIBLE) 的非法混合

php - 使用 php 创建多个表单插入并将其输入到 mysql