1

I am new to programming and I have a problem when storing the values ​​in an array using PDO.

I get a string from a form input:

  $brands = "Nike, Adidas, Reebok";

I get an array where the string separated by commas:

$pieces = explode(",", $brands);

I need to store each value in the array in different records within a table using PDO, something like this:

$statement = " INSERT INTO userbrands (Name, Email, Brand) VALUES (:name, :email, :brand)";
$sth = $db ->prepare($statement);
$sth -> execute(array(':name'=>$name, ':email'=>$email, ':brand'=>$pieces));

Thanks for answering a rookie question!

3
  • Use a for loop to iterate over the $pieces array. Commented Mar 14, 2013 at 17:37
  • 1
    Take note that the values will be Nike, [SPACE]Adidas and [SPACE]Reebok. To use explode and ignore whitespace, either loop through and use trim, or use preg_split('/,\s*/', $brands) instead. Commented Mar 14, 2013 at 17:39
  • You're right @h2ooooooo I will work on that, many thanks! Commented Mar 14, 2013 at 18:13

1 Answer 1

2
$statement = " INSERT INTO userbrands (Name, Email, Brand) VALUES (:name, :email, :brand)";
$sth = $db ->prepare($statement);
foreach ($pieces as $one_piece) {
  $sth -> execute(array(':name'=>$name, ':email'=>$email, ':brand'=>$one_piece));
}
Sign up to request clarification or add additional context in comments.

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.