简体   繁体   中英

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 = "john@example.com";
$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!

Bind within the foreach loop, assumed the variables exist:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM