GithubHelp home page GithubHelp logo

iamludal / mysql-querybuilder Goto Github PK

View Code? Open in Web Editor NEW
14.0 2.0 2.0 214 KB

๐Ÿ”ง A simple PHP query builder for MySQL queries.

Home Page: https://packagist.org/packages/ludal/mysql-querybuilder

License: MIT License

PHP 100.00%
php-query-builder php-querybuilder querybuilder pdo mysql mysql-query-builder php hacktoberfest

mysql-querybuilder's Introduction

๐Ÿ”ง MySQL QueryBuilder

PHPUnit Version PHP Version License Codacy Badge

composer require ludal/mysql-querybuilder

โ„น๏ธ Presentation

This is a PHP query builder for simple MySQL queries. It allows you to write them without using strings nor heredoc, which often breaks the code's cleanliness.

This package is designed to support MySQL DBMS. However, it may work with other DBMS (PostgreSQL, SQLite...), but I cannot guarantee that, so use it at your own risk.

๐Ÿ’ก Made with โค๏ธ in ๐Ÿ‡ซ๐Ÿ‡ท

๐Ÿ“˜ Usage

Getting Started

First, initialize a new instance of QueryBuilder.

$builder = new QueryBuilder();

๐Ÿ’ก You can also pass a PDO instance as a parameter to execute and fetch queries directly.

$pdo = new PDO($dsn, $login, $password);
$builder = new QueryBuilder($pdo);

From this instance, you can now build your query:

$select = $builder
  ->select()
  ->from('users')
  ->where('name = :name');

$update = $builder
  ->update('users')
  ->set(['name' => 'John'])
  ->where('id = 6');

Then, you can either:

  • Convert your query into a SQL string : toSQL()
  • Bind parameters: setParam('name', 'John'), setParams(['name' => 'John'])...
  • Execute the query : execute(), execute(['John'])...
  • Fetch the results of your query : fetch(), fetchAll(), fetch(PDO::FETCH_COLUMN)...
  • Get the rowCount : rowCount()
  • Get the PDO statement corresponding to your query : getStatement()
  • And more: see docs for a full reference
$select->toSQL(); // returns 'SELECT * FROM users'

$select->fetchAll(); // returns the rows fetched from the db

$select->getStatement(); // get the PDO statement, useful for handling errors

$update->execute(); // executes the UPDATE query

Supported Statements

  • SELECT
  • UPDATE
  • DELETE FROM
  • INSERT INTO

Supported Clauses

  • WHERE
  • GROUP BY
  • ORDER BY
  • LIMIT
  • OFFSET

Code Samples

$pdo = new PDO(...);
$qb = new QueryBuilder($pdo);

QueryBuilder::setDefaultFetchMode(PDO::FETCH_ASSOC);

// SELECT
$res = $qb
  ->select()
  ->from('users')
  ->where('id < 4', 'name = :name')
  ->orWhere('age < 12')
  ->orderBy('id', 'desc')
  ->limit(2)
  ->offset(1)
  ->fetchAll();

// INSERT
$insert = $qb
  ->insertInto('articles')
  ->values(['title' => 'Lorem ipsum', 'content' => 'Some content'])
  ->getStatement(); 

$insert->execute();
$insert->errorCode(); // or any other PDOStatement method

// UPDATE
$updated = $qb
  ->update('connections')
  ->set(['exp' => true, 'date' => date('Y-m-d')])
  ->where(['token' => $token])
  ->orderBy('date')
  ->limit(1)
  ->execute();

// DELETE
$rowCount = $qb
  ->deleteFrom('users')
  ->where('id > 5')
  ->orWhere('name = :name')
  ->orderBy('id', 'desc')
  ->limit(10)
  ->setParam(':name', 'John')
  ->rowCount(); // will execute, and return the rowCount

๐Ÿ“– Docs

Wiki under construction. ๐Ÿšง

๐Ÿ™ Acknowledgements

mysql-querybuilder's People

Contributors

dependabot-preview[bot] avatar iamludal avatar nimah79 avatar

Stargazers

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

Watchers

 avatar  avatar

mysql-querybuilder's Issues

Add a security paragraph in README

Add a security paragraph to inform that when using the array notation, it is protected against SQL injections

['name' => 'Ludal'] // Becomes: 'name = :_name'

`orderBy` as associative array

Replace the orderBy method signature to receive an associative array as an argument.

Example:

$this->builder
 ->select('*')
 ->from('users')
 ->orderBy(['name' => 'asc', 'id' => 'desc', 'age'])
 ->toSQL();

This would produce the following SQL:

SELECT * FROM users ORDER BY name ASC, id DESC, age ASC;

Param overriding value of another param with same name

Describe the bug
Parameter overriing the value of the previously set param (that has the same name)

To Reproduce

$id = 'old_id';
$values = ['id' => 'new_id'];

$builder
  ->update('users')
  ->set($values)
  ->where('id = :id')
  ->setParam(':id', $id); // will replace 'new_id' by 'old_id'

Expected behavior
One should be able to set any value with setParam without overriding the value of another param (that has the same name) from set().

Possible fix
Just add padding chars in set() method (eg: :_id instead of :id)

Add `JOIN` clause

Ideas of usage:

->select('*')
->from('users u')
->join('profile p', ['u.id = p.userId']) 

join($table, $conditions)

Tests inheritance

ClauseTest: don't have to run on itself, only through subclasses.

Autocomplete after "where"

Describe the bug
Autocomplete is broken after using where clause. This is because of the new WhereClause class.

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.