PDO full guide with examples and a complete crud code step by step 2022

    By: Thad Mertz
    2 years ago
    Category: PHPViews: 133

    Hi devs in this guide we are going to see PDO "PHP Data Objects". lets get started we are going to create a crud to see the deference and benefits of pdo.

    So how PDO secures our queries, Here is a example

    // Normal Query
    
    // Unsafe approach
    
    $id = 10;
    $posts = $pdo->query("SELECT * FROM blog WHERE blog_id='$id'"); // Here we are passing id directly in sql query which can be insecure.
    
    
    while($row = $posts->fetch())
    {
        echo $row->title."<br/>";
    }
    
    

    So when doing a query to database why not prepare it first and pass parameters in query instead direct variable.

    Let's see the "Insert query" using PDO.

     // Insert query.
    
    
            $post = $pdo->prepare("INSERT INTO blog(`title`, `description`) VALUES (:title, :details)");
            $post->execute([
                'title' => $title,
                'details' => $details,
            ]); 
    


    We defined named parameters

    :title  and :details both are parameters and we are setting values to these parameters 
    
    here
    
    $post->execute([
                'title' => $title,
                'details' => $details,
    ]); 
    

    Similar way we deal with update query

      $post = $pdo->prepare("UPDATE blog SET `description` = :details WHERE title=:title");
            $post->execute([
                'title' => $title,
                'details' => $details,
            ]);
    

    PDO also offer unnamed parameters, Note order you assign values to unnamed parameters matters.

    Here we use unnamed parameters to delete record.

     $post = $pdo->prepare("DELETE from blog WHERE id=?");
     $post->execute([$_GET['id']]);
    
    Here ? is unnamed parameter and gets value from $_GET['id']
    

    Hope this helps, Check our video guide for better understanding and working examples.