Posts

Creating a RESTful API in PHP

Image
  Preparation On my local machine I have created a folder called api in xampp > htdocs and inside it there is a file called index.php Now if you go to localhost/api you will get an empty response because the index.php is empty. Pretty URL The very first thing that we need to take care of is the urls in our project One of the key features of REST API is the way each url is responsible for one resource and one action Problem At the moment if I create a users.php then I have to go to  Problem At the moment if I create a users.php then I have to go to  localhost/api/users.php Then for each id of a user I have to create a new file localhost/api/users/ 1 .php localhost/api/users/ 2 .php Ans so on. There are 2 issues with this approach.  it’s ridiculously boring and time consuming to create a new file for each user The routes are ugly. All of them have .php at the end Solution Let’s solve that. As I mentioned I don’t want to use any framework and I want to use the simple...

CRUD operation in Database using PHP

  PDO replaces all previous database interaction approaches. Using PDO, you could easily perform CRUD and related DBMS operations. In effect, PDO acts as a layer separating database-related operations from the rest of the code. Connectivity One of the most important benefits of PDO is the simple database connectivity. Consider the following code snippet used to set up connections with the database. <?php $server = “localhost”; $user = “root”; $password = “”; $db = “phppdo”; try { $dbcon = new PDO(“mysql:host=$server;dbname=$db”, $user, $password); $dbcon->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_OBJ); } catch (PDOException $e) { echo “Connection Failed: “ . $e->getMessage(); } In the above code snippet, notice that the DBMS is MySQL. However, if the DBMS changes to MS SQL Server, the only change will be the replacement of MySQL with mssql. Creating a Table With PDO To create a table, first declare a query string and then execute it with the exec function as no ...