Inserting Records with PHP PDO
Here in this step, you will learn about inserting and deleting records with PDO. You will also learn about getting last insert id with PDO.
Here I’m going to use two PDO methods that are query method and exec method to insert and delete queries and also you will learn about the difference between query method and exec method.
Other Articles in Learn PHP PDO
- PDO Basics
- Fetching Records with PDO
- Inserting Records with PDO
- Deleting Records with PDO
- PDO Prepared Statements
- CRUD Application in PHP PDO
1. Inserting Records in PDO with Query Method
First of all, I’m inserting a new record with query method. And here I’m passing values directly in the SQL query. After executing query method, I’m using var_dump to print result.
Here is the code to insert a record in the database with PHP PDO.
1 2 3 |
$sql = "INSERT INTO crud (firstname, lastname, email, gender, age) VALUES('Vivek', 'Vengala', '[email protected]', 'male', '28')"; $result = $db->query($sql); var_dump($result); |
After executing above code you will see the SQL query on the screen. To proceed to next steps we should know the query is successful or not. To get this kind of response I’ll use exec method instead of the query method.
2. Inserting Records in PDO with Exec Method
In the previous step, we are not getting the correct response to know whether the query is successful or not. For that, I’m using exec method.
With exec method, you can see the no of affected rows.
1 2 3 |
$sql = "INSERT INTO crud (firstname, lastname, email, gender, age) VALUES('Vivek', 'Vengala', '[email protected]', 'male', '28')"; $result = $db->exec($sql); var_dump($result); |
After loading the above code, you will see the number of affected records. With above code I’m inserting one record, you will see the output as 1.
3. Getting Last Insert ID after Query
After insert query to get the id of the record inserted, you can use the lastInsertID method.
Here is the code to get last insert id.
1 |
$db->lastInsertID(); |
Use above code with insert query to display the last insert id.