PHP MySQL PDO Insert with name place holder and use associative array
From w3cyberlearnings
Contents |
PHP PDO Insert with name place holder and an associative array
Use an associative array for a name place holder to insert a new record.
Syntax PDO Insert
$sql = "INSERT INTO user_infor(first_name, last_name, email) VALUE(:first,:last,:email)"; $sq = $db->prepare($sql); $insert_array['first'] = 'George'; $insert_array['last'] = 'Washington'; $insert_array['email'] = '[email protected]'; $sq->execute($insert_array);
Example 1
<?php $dns = 'mysql:host=localhost;dbname=w3cyberlearning'; $user = 'user2000'; $pass = 'password2000'; $db = new PDO($dns, $user, $pass); $sql = "INSERT INTO user_infor(first_name, last_name, email) VALUE(:first,:last,:email)"; $sq = $db->prepare($sql); $insert_array['first'] = 'George'; $insert_array['last'] = 'Washington'; $insert_array['email'] = '[email protected]'; if ($sq->execute($insert_array)) { echo 'Successfully insert record <br/>'; echo "insert_id " . $db->lastInsertId(); } else { echo 'Failed to insert record <br/>'; } ?>
Output
Successfully insert record insert_id 3