Home > database >  How to add each word or get string as separate entry to database
How to add each word or get string as separate entry to database

Time:06-01

$stuffname=$_GET['stuffname'];
$pieces = explode(" ", $stuffname);

$pieces can have any number of words in it.

I want to loop this query so that each word is added from pieces as a separate entry into the table keywords

$query=$con->prepare("INSERT INTO keywords (stuffname) VALUES (?)");
$query->execute([$pieces]);

Thanks for your time

CodePudding user response:

It's unclear if you've tried anything or where you got stuck, but this should be very simple with a loop.

Either

  1. execute a separate INSERT for each new row
    $query = $con->prepare("INSERT INTO keywords (stuffname) VALUES (?)");

    foreach ($pieces as $piece)
      $query->execute([$piece]);{
    }

or

  1. Try to build a single INSERT with multiple sets of values:
    $sql = "INSERT INTO keywords (stuffname) VALUES ";
    $vals = "";
    
    foreach ($pieces as $piece)
    {
      $vals .= ($vals != "" ? "," : "")."(?)";
    }
    
    $query = $con->prepare($sql.$vals);
    $query->execute([$pieces]);
  • Related