Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

$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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
    $query->execute([$pieces]);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading