Skip to content

Instantly share code, notes, and snippets.

@terrymun
Created August 19, 2015 07:41
Show Gist options
  • Save terrymun/af7f98d57fd5195c76d9 to your computer and use it in GitHub Desktop.
Save terrymun/af7f98d57fd5195c76d9 to your computer and use it in GitHub Desktop.
Binding parameters or values to placeholders within the for loop
<?php
// Assuming that database connection is already open
// You have an array of userdata
$userData = array([1] => 'johndoe', [2] => '[email protected]', [3] => 'USA');
// Prepare statement
$stmt = $db->prepare("INSERT INTO users (user, email, country) VALUES (?, ?, ?)");
// For loop
// Bind param binds the REFERENCE, remember to modify array (&$value)
foreach($userData as $key=>&$value) {
$stmt->bindParam($key, $value);
}
$stmt->execute();
?>
<?php
// Assuming that database connection is already open
// You have an array of userdata
$userData = array([1] => 'johndoe', [2] => '[email protected]', [3] => 'USA');
// Prepare statement
$stmt = $db->prepare("INSERT INTO users (user, email, country) VALUES (?, ?, ?)");
// For loop
// Bind param binds the VALUE, array modification not required ($value)
foreach($userData as $key=>$value) {
$stmt->bindValue($key, $value);
}
$stmt->execute();
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment