PHP Classes

File: read_by_condition.php

Recommend this page to a friend!
  Classes of Channaveer Hakari   PHP PDO CRUD Example   read_by_condition.php   Download  
File: read_by_condition.php
Role: Example script
Content type: text/plain
Description: Example script
Class: PHP PDO CRUD Example
Example code to implement CRUD operations with PDO
Author: By
Last change:
Date: 8 months ago
Size: 842 bytes
 

Contents

Class file image Download
<?php
require_once './db.php';

/** Usually you do this */
// $userId = filter_input(INPUT_GET, 'user_id', FILTER_VALIDATE_INT);
/** For the sake of demo I am hard coding */
$userId = 1;
try {
   
$userQuery = $pdo->prepare("
        SELECT
            `id`, `first_name`, `last_name`, `email`, `password`
        FROM
            `users`
        WHERE
            `id` = :user_id
    "
);
   
$userQuery->execute([
       
':user_id' => $userId,
    ]);
   
$user = $userQuery->fetch(PDO::FETCH_ASSOC);
   
/*
        $user = $userQuery->fetch(PDO::FETCH_OBJ);
            OR
        $user = $userQuery->fetchObject();
     */
   
if (!$user) {
        throw new
Exception('User details not found');
    }

    echo
'<pre>';
   
print_r($user);
} catch (
Exception $e) {
   
/** Handle all your errors here */
   
exit($e->getMessage());
}