Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6164823
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 23, 20262026-05-23T22:03:36+00:00 2026-05-23T22:03:36+00:00

My web application currently has do execute simple queries: simple CRUD operations, counting,… A

  • 0

My web application currently has do execute simple queries: simple CRUD operations, counting,…

A few months ago, someone recommended me here to write a simple PDO wrapper for this (to avoid writing try/catch, prepare(), execute(), etc. each time a query should be executed). This example method was shown (I’ve made some changes so I could use it in my own project):

public function execute() {
    $args  = func_get_args();
    $query = array_shift($args);
    $result = false;

    try {
      $res = $this->pdo->prepare($query);
      $result = $res->execute($args);
    } catch (PDOException $e) { echo $e->getMessage(); }

    return $result;
  }

As I need to perform more operations (executing queries, retrieving 1 record, retrieving multiple records, counting results) I created a method for all of these:

  public function getMultipleRecords() {
    $args  = func_get_args();
    $query = array_shift($args);
    $records = array();

    try {
      $res = $this->pdo->prepare($query);
      $res->execute($args);
      $records = $res->fetchAll();
    } catch (PDOException $e) { echo $e->getMessage(); }

    return $records;
  }

  public function getSingleRecord() {
    $args  = func_get_args();
    $query = array_shift($args);
    $record = array();

    try {
      $res = $this->pdo->prepare($query);
      $res->execute($args);
      $record = $res->fetch();
    } catch (PDOException $e) { echo $e->getMessage(); }

    return $record;
  }

  public function execute() {
    $args  = func_get_args();
    $query = array_shift($args);
    $result = false;

    try {
      $res = $this->pdo->prepare($query);
      $result = $res->execute($args);
    } catch (PDOException $e) { echo $e->getMessage(); }

    return $result;
  }

  public function count() {
    $args  = func_get_args();
    $query = array_shift($args);
    $result = -1;

    try {
      $res = $this->pdo->prepare($query);
      $res->execute($args);
      $result = $res->fetchColumn();
    } catch(PDOException $e) { echo $e->getMessage(); }

    return $result;
  }

As you see, most of the code is the same. Only 2 lines of code are different for each method: the initialisation of $result (I always want to return a value, even if the query fails) and the fetching. Instead of using 4 methods, I could write just one of them and pass an extra parameter with the type of action. That way, I could use a bunch of if/else statements of a switch statement. However, I think the code can get messy. Is this a good way for solving this problem? If not, what would be a good solution to it?

The second problem I have (which is why I’m working on this class right now) is that I want to use prepared statements with the LIMIT SQL statement. However, it is not possible to do this:

$res = $pdo->prepare("SELECT * FROM table LIMIT ?");
$res->execute(array($int));

The variabele will be quoted for some reason (and so the query will fail), as explained here:
https://bugs.php.net/bug.php?id=40740

The solution seems to use bindValue() and use the int datatype as a parameter:
http://www.php.net/manual/de/pdostatement.bindvalue.php

I could rewrite the method(s) to support this, but I would also need to use an extra parameter. I can’t just use $db->execute($sql, $variable1, $variable2); anymore as I need to know the data type.

What’s the best way to solve this?

Thanks

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-23T22:03:36+00:00Added an answer on May 23, 2026 at 10:03 pm

    How about creating a class with methods that you can chain (for clarity, I’ve removed error checking):

    class DB {
    
        private $dbh;
        private $stmt;
    
        public function __construct($user, $pass, $dbname) {
            $this->dbh = new PDO(
                "mysql:host=localhost;dbname=$dbname",
                $user,
                $pass,
                array( PDO::ATTR_PERSISTENT => true )
            );
        }
    
        public function query($query) {
            $this->stmt = $this->dbh->prepare($query);
            return $this;
        }
    
        public function bind($pos, $value, $type = null) {
    
            if( is_null($type) ) {
                switch( true ) {
                    case is_int($value):
                        $type = PDO::PARAM_INT;
                        break;
                    case is_bool($value):
                        $type = PDO::PARAM_BOOL;
                        break;
                    case is_null($value):
                        $type = PDO::PARAM_NULL;
                        break;
                    default:
                        $type = PDO::PARAM_STR;
                }
            }
    
            $this->stmt->bindValue($pos, $value, $type);
            return $this;
        }
    
        public function execute() {
            return $this->stmt->execute();
        }
    
        public function resultset() {
            $this->execute();
            return $this->stmt->fetchAll();
        }
    
        public function single() {
            $this->execute();
            return $this->stmt->fetch();
        }
    }
    

    You can then use it like this:

    // Establish a connection.
    $db = new DB('user', 'password', 'database');
    
    // Create query, bind values and return a single row.
    $row = $db->query('SELECT col1, col2, col3 FROM mytable WHERE id > ? LIMIT ?')
       ->bind(1, 2)
       ->bind(2, 1)
       ->single();
    
    // Update the LIMIT and get a resultset.
    $db->bind(2,2);
    $rs = $db->resultset();
    
    // Create a new query, bind values and return a resultset.
    $rs = $db->query('SELECT col1, col2, col3 FROM mytable WHERE col2 = ?')
       ->bind(1, 'abc')
       ->resultset();
    
    // Update WHERE clause and return a resultset.
    $db->bind(1, 'def');
    $rs = $db->resultset();
    

    You could alter the bind method to accept an array or associative array if you prefer, but I find this syntax quite clear – it avoids having to build an array. The parameter type checking is optional, as PDO::PARAM_STR works for most values, but be aware of potential issues when passing null values (see comment in PDOStatement->bindValue documentation).

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am currently working on a web application. I was just wondering which has
The web application I am working currently has an File import logic. The logic
Our workflow currently has developers working on locally hosted copies of our web application
I am creating an android application which has to execute web requests in the
I'm currently doing web application development in PHP. Management has told us we're standardizing
I have a web application that currently sends emails. At the time my web
I am designing a web application using GWT currently, which is also the first
I am building a web application that is currently PHP with MySQL. There is
The web-based application I’m currently working on is growing arms and legs! It’s basically
I am currently building an internal web application used in a factory/warehouse type location.

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.