GithubHelp home page GithubHelp logo

pdo-wrapper's Introduction

PDO Wrapper

This PDO wrapper, is a collection of methods for working with a database this includes selecting, inserting, updating and deleting records.

V2+ has been rewritten for the old docs please see V1 branch

Latest Version on Packagist Total Downloads

Logo

This PDO wrapper, is a collection of methods for working with a database this includes selecting, inserting, updating and deleting records.

V2+ has been rewritten for the old docs please see V1 branch

Upgrade from V1

Version 2 is now namespaced as Dcblogdev instead of Daveismyname

Also the methods get() and select() have been removed.

Instead of ::get() a new instance of the class used new Database($args)

Select has been replaced with ->rows() and ->row() or ->run()

Quick Reference

//create table
$db->raw("CREATE TABLE demo (id int auto_increment primary key, name varchar(255))");

//use PDO directly
$db->getPdo()->query('Select username FROM users')->fetchAll();

//use run to query and chain methods
$db->run("SELECT * FROM users")->fetchAll();
$db->run("SELECT * FROM users")->fetch();
$db->run("SELECT * FROM users WHERE id = ?", [$id])->fetch();
//select using array instead of object
$db->run("SELECT * FROM users")->fetch(PDO::FETCH_ASSOC);

//get by id
$db->getById('users', 2);

//get all rows
$db->rows("SELECT title FROM posts");
//get all rows with placeholders
$db->rows("SELECT title FROM posts WHERE user_id = ?", [$user_id]);

//get single row
$db->row("SELECT title FROM posts");
//get single row with placeholders
$db->row("SELECT title FROM posts WHERE user_id = ?", [$user_id]);

//count
$db->count("SELECT id FROM posts");
$db->count("SELECT id FROM posts WHERE category_id = ?", [$category_id]);

//insert
$id = $db->insert('users', ['username' => 'Dave', 'role' => 'Admin']);

//last inserted id
$db->lastInsertId()();

//update
$db->update('users', ['role' => 'Editor'], ['id' => 3]);

//delete from table with a where claus and a limit of 1 record
$db->delete('posts', ['type_id' => 'draft'], $limit = 1);

//delete from table with a where claus and a limit of 10 record
$db->delete('posts', ['type_id' => 'draft'], $limit = 10);

//delete all from table with a where claus and a limit of 10 record
$db->delete('posts', ['type_id' => 'draft'], null);

//delete all from table
$db->deleteAll('posts');

//delete by id from table
$db->deleteById('posts', 2);

//delete by ids from table
$db->deleteById('posts', '2,4,7');

//truncate table
$db->truncate('posts');

Install

Using composer include the repository by typing the following into a terminal

composer require dcblogdev/pdo-wrapper

Set the DB credentials. Finally, create an instance of the classes.

use Dcblogdev\PdoWrapper\Database;

// make a connection to mysql here
$options = [
    //required
    'username' => '',
    'database' => '',
    //optional
    'password' => '',
    'type' => 'mysql',
    'charset' => 'utf8',
    'host' => 'dev',
    'port' => '3309'
];

$db = new Database($options);

Accessing PDO You can call getPdo()` to get access to PDO directly:

$db->getPdo()

This allows to chain calls:

$db->getPdo()->query($sql)->fetch();

Querying

All queries use prepared statements, calling ->run() returns a PDO option that can be chained:

Select multiple records:

$db->run("select * FROM users")->fetchAll();

Select a single record:

$db->run("select * FROM users")->fetch();

Select multiple records using ->rows

$db->rows("select * FROM table");

Select single record using ->row

$db->row("select * FROM table");

To select records based on user data instead of passing the data to the query directly use a prepared statement, this is safer and stops any attempt at sql injections.

Names placeholders

$db->row("select username FROM users WHERE id = :id and email = :email", ['id' => 1, ':email' => '[email protected]']);

Annonomus placeholders

$db->row("select username FROM users WHERE id = ? and email = ?", [1, '[email protected]']);

The above query will return the username from a users table where the id and email match. The id and email is passed seperartly in an array.

Instead of passing in an id and email to the query directly a placeholder is used :id and :email (or ? can be used) then an array is passed the keys in the array matches the placeholder and is bound, so the database will get both the query and the bound data.

Data returned from the query will be returns as an object this can be changed by passing a third param containing PDO::FETCH_ASSOC.

To use the object loop through it, a typical example:

$rows = $db->rows("firstName, lastName FROM username ORDER BY firstName, lastName");
foreach ($rows as $row) {
    echo "<p>$row->firstName $row->lastName</p>";
}

Select Single Record

Using row() will return only a single result. Like rows it accepts params being passed in an array as a second argument.

Names placeholders

$db->row("column FROM table where id=:id", ['id' => 23]);

Anonymous placeholders

$db->row("column FROM table where id=?", [23]);

Another way to select a single record using the table and id by calling ->getById

$db->getById('users', $id);

Raw

A raw query is a query that does not run through a prepared statement and will execute the query passed directly. Useful when creating a table.

$db->raw("CREATE TABLE IF NOT EXISTS users (
  id INT(11) NOT NULL AUTO_INCREMENT,
  firstName VARCHAR(255) NOT NULL,
  lastnName VARCHAR(255) NOT NULL,
  email VARCHAR(255) NOT NULL,
  PRIMARY KEY (id))"
);

Count

To count records call the count method. This method expects the table name and column name (optional).

$db->count('users');

If the table has no column id

$db->count('users', 'user_id');

Insert

Data is inserted by calling the insert method it expects the table name followed by an array of key and values to insert in to the database.

$data = [
    'firstName' => 'Joe',
    'lastnName' => 'Smith',
    'email' => '[email protected]'
];
$db->insert('users', $data);

The insert automatically returns the last inserted id by returning 'lastInsertId' to collect the id:

$id = $db->insert('users', $data);

Updating

To update an existing record the update method is called. This method expects the table, array of data to update, and a second array containing the where condition.

$data = [
    'firstName' => 'Joe',
    'lastnName' => 'Smith',
    'email' => '[email protected]'
];
$where = ['id' => 2];
$db->update('users', $data, $where);

Or:

$update = [ 
	'data' => [
	    'firstName' => 'Joe',
	    'lastnName' => 'Smith',
	    'email' => '[email protected]'
	],
	'where' => [
        'id' => 2
    ]
];

$db->update('users', $update['data'], $update['where']);

Delete

To delete records call the delete method. This method expects the table name and an array of the where condition.

$where = ['id' => 2];
$db->delete('users', $where);

This will delete a single record to set the limit pass a third parameter containing the number to limit to or to remove the limit pass null as a third param.

$db->delete('users', $where, 10);  //delete 10 records matcing the where
$db->delete('users', $where, null); //delete all records matching the where

Delete All

To delete all records for a given table

$db->deleteAll('users');

Delete by Id

To delete a record by its table and id

$db->deleteById('users', $id);

Delete Multiple In

To delete multiple records where ids are in a specific column, this uses WHERE id IN (4,5,6)

$db->deleteByIds('users', 'id', '4,5,6');

Truncate

To empty a table of all contents call the truncate method. Passing only the table name.

$db->truncate('users');

pdo-wrapper's People

Contributors

adalenv avatar daveismynamecom avatar dcblogdev avatar digitalstars avatar dizzysquirrel avatar ezetojo avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pdo-wrapper's Issues

Close/Free for Performance?

Hello david. I loved the code.
First of all, it's worth clarifying that I'm a newbie in PHP.
I have tried some times to use PHP in previous projects (in shared hostings) and they have caught my attention because the scripts consumed a lot of memory, I remember that something I did to solve it was to close the queries and connections.
You do not need any of that in this wrapper?
I would appreciate it if you could clarify it to me.
Greetings.

How to use with JOIN in SQL?

I cannot use with LEFT JOIN.

The SQL: $db->getPdo()->query("SELECT users.user_id, users.pw, employee.phone, employee.email FROM users LEFT JOIN employee ON users.user_id = employee.em_id WHERE employee.phone = :phone OR employee.email = :email", [':phone' => $usrname, ':email' => $usrname])->fetch()

Error: PHP Fatal error: Uncaught PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'phone' in 'where clause' in

Where on select

i keep playing with your wrapper, it's helping me a lot to learn php!

now im trying to make a dinamic where, something like
$db->select("SELECT * FROM table",$where);

should i add a new array to the select function?

mulitiple delete

your wrapper are amazing, clean & simple, save me a lot of time.
will you gonna add multiple delete method?
currently i use raw method to delete record with different id.
my code as below.

$ids = implode("','",$_POST['ids']);
$db->raw("delete from '.$table.' where cm_id in('".$ids."')");
echo json_encode($ids);

not use IN operator

sql exapmle SELECT * FROM Table WHERE id IN (1, 2, 3)
pdo example $db->rows("select * from table where id IN ?",[1,2,3]);
pdo example2 $db->rows("select * from table where id IN ?",['(1,2,3)']);
testing rows other raw and run method not working

Merge in update() method will omit data

Line 179 - 183:

`       //merge data and where together
        $collection = array_merge($data, $where);

         //collect the values from collection
        $values = array_values($collection);`

Merge array $data and $where if they have same columns -> lost data.

The problem will occur when we want to update a column which appear in where (or in array $values). Eg.:

UPDATE contact SET phone = '012-345-6789', first_name='Patrick' WHERE phone = 012-345-9950';

How to solve the problem?

Update method improved

If you set a where property that appers in data array, the array merge remove duplicates and the bind params throw error.
Example:

$db->update("table",["gid" => "XXXXXX", "group_gid" => "YYYYYY"],["gid" => "XXXXXX"]);

With these, $values array only have 2 items to bind so throw SQL ERROR.

Just rewrite this function like this:

public function update(string $table, array $data, array $where): int {
  //collect the values from data
  $values = array_values($data);
  
  //setup fields
  $fieldDetails = [];
  foreach ($data as $key => $value) {
	  $fieldDetails[] = "$key = ?";
  }
  $fieldDetails = implode(",", $fieldDetails);
  
  //setup where
  $whereDetails = [];
  foreach ($where as $key => $value) {
	  $whereDetails[] = "$key = ?";
	  //append values from where
	  $values[] = $value;
  }
  $whereDetails = implode(" AND ", $whereDetails);
  
  $stmt = $this->run("UPDATE $table SET $fieldDetails WHERE $whereDetails", $values);
  
  return $stmt->rowCount();
}

Thanks for your time!

Missing attribute to get the rowCount value when using update

I just found this little but so useful PDO wrapper. However, the rowCount was always returning 0 when I was using the $db->update method.

I fixed changing line 46 to:

$instance = new Database("$type:host=$host;dbname=$name;charset=utf8", $user, $pass, array(PDO::MYSQL_ATTR_FOUND_ROWS => true));

Cheers!

Need to be able to specify port and charset from outside of class

Hi,
Need to be able to specify port and charset from outside of class when connecting to MySQL server (Database::get(... array options maybe ...)), would be really great if you could implement the feature, that way no need to fork the file and always use the original file with any new version, cheers

Unclear how to implement SHOW TABLES query

Hi!

Love your PDO Wrapper! I am successfully using it in a large project
and it has significantly cut down on my code size.

I hope you'll pardon my ignorance here, but it is unclear to me how I go
about reading in and storing the results of TABLE SHOW using the
wrapper. In regular PDO code, I am using the following...

//Execute the SHOW TABLE query
 try {
     $conn = new PDO(...);
     $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
     $stmt = $conn->prepare("SHOW TABLES");
     $stmt->execute();
 }
 catch(PDOException $e){
     echo "Error: " . $e->getMessage();
 }

 //Build array from the resulting SQL file rows

 $table= [];

 $row = 0;
 while ($r = $stmt->fetch(PDO::FETCH_NUM)) {
     $table[$row] = $r[0];
     $row = $row + 1;
 }       

This is the last piece that will allow me to have converted the entire
project to your wrapper. Any guidance will be appreciated.

Thx,

Bill

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.