nxet
nxet

Reputation: 738

foreach in PDO prepared statement


I would like to have a bit of clarification about prepared statements, and how they behave when assembled in other ways.

The sample code below is from Straight out this W3 entry. My problem is that, having many more values than the four provided in this example, I'd love to store them in an array and then run a foreach to prepare each string.

$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) 
VALUES (:firstname, :lastname, :email)");
$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':lastname', $lastname);
$stmt->bindParam(':email', $email);

// insert a row
$firstname = "John";
$lastname = "Doe";
$email = "[email protected]";
$stmt->execute();

// insert another row
$firstname = "Mary";
etc



Would the edit below be safe for application, or does it crack the whole point of prepared statements?

$stuff = array("firstname", "lastname", "email");
foreach ($stuff as $singlestuff) {
$singlestuff1 = ':'.$singlestuff;
$singlestuff2 = '$'.$singlestuff;
$stmt = $conn->prepare("INSERT INTO MyGuests ($singlestuff1) ) VALUES ($singlestuff2)");
$stmt->bindParam($singlestuff1, $singlestuff2);
}


Sorry for any macroscopic mistake, the code is just an illustration of the concept.
Thanks in advance!

Upvotes: 0

Views: 881

Answers (1)

code-kobold
code-kobold

Reputation: 824

Bind within the foreach loop, assumed the variables exist:

foreach ($stuff as $singlestuff) {
    $stmt->bindParam(':' . $singlestuff, $$singlestuff);
}

Upvotes: 0

Related Questions