How to use PDO to insert data into the database?

1109 0

$1*/ mo hosting! Get going with GoDaddy!

The SQL code for the users table:

1) Write a regular SQL query but, instead of values, put named placeholders. For example:

The use of placeholders is known as prepared statements. We use prepared statements as templates that we can fill later on with actual values.

2) Prepare the query:

3) Bind the placeholders to the variables:

You can add a third parameter which filters the data before it reaches the database:

  • PDO::PARAM_STR is used for strings.
  •  PDO::PARAM_INT is used for integers.
  • PDO::PARAM_BOOL allows only boolean (true/false) values.
  •  PDO::PARAM_NULL allows only NULL datatype.

4) Assign the values to the variables.

5) Execute the query:

6) Check that the insertion really worked:

If the last inserted id is greater than zero, the insertion worked.

All code together now:

For localhost Database name is : pdoanuj
Sql file available inside the package.




In this article

Join the Conversation