Created
August 19, 2015 07:41
-
-
Save terrymun/af7f98d57fd5195c76d9 to your computer and use it in GitHub Desktop.
Binding parameters or values to placeholders within the for loop
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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(); | |
| ?> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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