Jump to: navigation, search

PHP MySQL PDO Insert with question mark place holder

From w3cyberlearnings

Contents

PHP PDO Insert Record with question mark place holder

Use question mark place holder to insert a new record.

Syntax PDO

$sql = "INSERT INTO user_infor(first_name, last_name, email) VALUE(?,?,?)";
$sq = $db->prepare($sql);

$first_name = 'Alex';
$last_name = 'Gate';
$email = '[email protected]';

$sq->execute(array($first_name, $last_name, $email));

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(?,?,?)";
$sq = $db->prepare($sql);

$first_name = 'Alex';
$last_name = 'Gate';
$email = '[email protected]';

if ($sq->execute(array($first_name, $last_name, $email))) {
	echo 'Successfully insert record <br/>';
	echo "insert_id ". $db->lastInsertId();
} else {
	echo 'Failed to insert record <br/>';
}
?>

Output

Successfully insert record 
insert_id 2


Related Links


Navigation
Web
SQL
MISC
References