This post explains how to build a CRUD (Create-Read-Update-Delete) procedures in PHP and MySQL using PDO (PHP Data Objects). PDO is a PHP advance version that implements an intermediate to using MySQL databases in PHP. PDO is compact and strong. There are several great concepts of PDO. The greatest one is, it’s cross-database compatible. You don’t need to change your query function if you switch database server for your project. PDO extension helps different databases like MS SQL, MySQL, Oracle, SQLite, etc.
Error handling is another greater benefit of PDO extension. Using this we can able to write a code with try/catch block. It kept error logs as a file and user-friendly messages are displayed on a page. PDO also help to use prepared statements and stored methods. The important advantage of prepared statements is that you just need to prepare a query once and we can use many times with the same or different parameters.
In this post, Here we just delete the data from a database with the help of primary key and PDO connection object.
Step 1: Create a PDO connection file with database connection details and link with created database table.
1 2 3 4 5 6 7 |
<?php $DB_host = 'localhost'; $DB_username = 'root'; $DB_password = ''; $DB_name = 'li_demo'; $pdo_conn = new PDO( 'mysql:host='.$DB_host.';dbname='.$DB_name, $DB_username, $DB_password ); ?> |
Step 2: Initially, we need to get the primary key id value and write a delete query with that key value.
1 2 3 4 5 6 7 8 9 10 11 |
<?php $post_id = $_REQUEST['post_id']; $pdo_statement = $pdo_conn->prepare("delete from li_ajax_post_load where post_id=" . $post_id); $result = $pdo_statement->execute(); if (!empty($result) ){ echo '<div class="alert alert-success">Data deleted successfully.</div>'; } else{ echo '<div class="alert alert-danger">Data deleting failed.</div>'; } ?> |