1

This is code for insert dynamic data to mysql database.

    $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(); 

I used implode(", ", (array)$name[$i]) to returns a string from $name by comma but when print_r($test); like this:

AlexBrownHelloHugo

I got 2 problems and hope your help:

  • Result when print_r($test); is Alex,Brown,Hello,Hugo
  • Store $test [Alex,Brown,Hello,Hugo] same row into dabase.

Thanks all.

5
  • What's the value of $_POST['name']? Commented Mar 2, 2019 at 9:31
  • Value of $_POST['name'][0] is Alex, _POST['name'][1] is Brown ... Commented Mar 2, 2019 at 9:33
  • Then your $name itself is an array which you can convert into a string using implode(",", $name) outside the loop. Use the string to insert as well. Commented Mar 2, 2019 at 9:41
  • 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. Commented Mar 2, 2019 at 9:45
  • I also don't know why you would use for instead of foreach which would be way easier. Commented Mar 2, 2019 at 9:48

2 Answers 2

1

Something like this:

$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');
         }              
    }
}

I wanted to repost this comment I made:

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

UPDATE

And this one

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.

So you may be able to do just this:

//$_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';
      }              
}

With no loop, because when you loop over the count of names, your inserting the same data each time, up to the number of items in the names variable.

Explaining your code

So with my example data $_POST['name'] = ['foo','bar', ...] and a simplified version of your original code, you would be doing this:

Assuming you meant implode($name) and not implode($name[$i]) in your original code, which is the only sane thing if your data looks like my example data

 //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";
    }
}

Outputs:

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

Sandbox

If should be obvious but if you changed this line $test= implode(", ", (array)$name); to $test= '['.implode(',', (array)$name).']; in the above code the output would be this:

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

Which still saves it more then one time. So we need to dump that loop, which basically forces us into the code I put at the top of this update.

Hopefully that all makes sense.

Cheers

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for your help. It worked but it can't store $test in Database
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.
but it can't store $test in Database I didn't modify any of the DB stuff, so if it saved before it should still work now.
Can you please help me store it in database?
Sure, but this doesn't help me but it can't store $test in Database, nor does the lack of example data for $name. Not to mention I have no idea if it originally stored the data in there or not.
0

Try this code, in fact your $_POST['name'] store your value as an array, so you don't need to cast it.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.