0

Sorry if this seems like a simple question but I've searched high and low on Google and Stackoverflow and while there are answers to similar questions, but nothing exactly like what my current situation is. In addition, I just recently returned to programming and first time in ever started using PDO and prepared statements so I've not mastered the art yet.

I have the following code, generating the SQL: (I will have the same code to generate the UPDATE versions to later update these insertions)

    if(isset($vars['benefits']))
    {
        foreach($vars['benefits'] as $benefit)
        {
            $sql['benefits'][] = "INSERT INTO " . BENEFITS_TABLE . " (benefit) VALUES ('{$benefit['benefit']}')";
        }
    }

    if(isset($vars['sliteratures']))
    {
        foreach($selectedIDs as $litID)
        {
            $sql['literature'][] = "INSERT INTO " . PRODLIT_TABLE . " (productID, literatureID) VALUES ('{$productID}', '{$litID}')";
        }
    }

Which obviously creates the dynamic amount of the query... and now I'm trying to convert it so I could prepare/bind the values (The columns is a hard-coded array while the values are retrieved VIA POST from an HTML form).

I don't know what is the best way to come by doing this. Or how to do it properly might be a better way to phrase that.

I could do that in a loop for each query separately. Like so:

    if(isset($vars['benefits']))
    {
        foreach($vars['benefits'] as $benefit)
        {
            $sql = "INSERT INTO " . BENEFITS_TABLE . " (benefit) VALUES (:benefit)";

            $stmt = $db->prepare($sql);
            $stmt->bindParam(":benefit", $benefit['benefit'], PDO::PARAM_STR);
            $stmt->execute();
        }
    }

And the other query likewise, but that puts the SQL operations in a loop. Is that a bad approach?

There would never be a drastic amount of INSERTS. The most would be like 10 for benefits and 3 or 4 for literature so I imagine doing it all in a loop wouldn't effect me much in terms of performance, but for future reference, what would be the best way to come by this effectively?

Thanks for any constructive input.

ezw
  • 338
  • 2
  • 12

0 Answers0