Inserting Data into the Database
Explore how to insert data into a PHP database using PDO by writing SQL queries with placeholders, preparing statements, binding variables, assigning values, and executing inserts. You will also learn to verify successful database insertions ensuring reliable data handling.
In this lesson, we’ll learn the different phases of inserting data into the database. We’ll see how to write queries, bind placeholders, assign values to variables, and finally execute them.
Step 1: Write a query
Write a regular SQL query but, instead of values, put named placeholders. For example:
$sql = "INSERT INTO `users`
(`name`, `phone`, `city`,
`date_added`)
VALUES
(:name,:phone,:city,:date)";
The use of placeholders is known as prepared statements. We use prepared statements as templates that we can later fill with actual values.