Prepare records to be inserted to a MySQL database using the PDO PDO prepare()
function in PHP, then use the PDOStatement execute()
function to perform the query.
Requirements:
- PHP
- PHP Data Objects
- PDO Drivers
- MySQL Functions (PDO_MYSQL)
- MySQL INSERT Statement
How to insert new records to a MySQL database using PDO in PHP.
Make sure the connection to MySQL Database have already been successfully made. And assign the connection object to variable $dbh
.
The objective is to add a new record using the named (:name)
parameter marker.
Consider below as the employees TABLE inside a MySQL DATABASE.
$first_name = 'Steven';
$last_name = 'Raymonds';
$sth = $dbh->prepare(
"INSERT INTO
employees
(first_name, last_name)
VALUES
(:first_name, :last_name)
"
);
$sth->execute(
array(
":first_name"=>$first_name,
":last_name"=>$last_name
)
);
Result.
Next goal is to add another new record using the question mark (?)
parameter marker.
$first_name= 'Michelle';
$last_name = 'Walters';
$sth = $dbh->prepare(
"INSERT INTO
employees
(first_name, last_name)
VALUES
(?, ?)
"
);
$sth->execute(array($first_name, $last_name));
Result.
Notes:
- Always sanitize user inputs.
Leave a Reply