GithubHelp home page GithubHelp logo

giovanniramos / pdo4you Goto Github PK

View Code? Open in Web Editor NEW
75.0 13.0 33.0 1.24 MB

PDO4You is a class that implements the Singleton design pattern for connecting the database using the PDO extension (PHP Data Objects)

Home Page: http://giovanniramos.github.com/PDO4You

License: MIT License

PHP 99.35% Shell 0.65%

pdo4you's Introduction

Leia a documentação em Português


PDO4You

Latest Stable Version Build Status Gittip donate button Flattr donate button PayPal donate button

This class is based on the PDO, which is a PHP extension that allows developers to create portable code, so as to cater for most popular databases. Being MySQL, PostgreSQL, SQLite, Oracle, Microsoft SQL Server, Sybase.

Alternatively been added in version 3.0 support for the MariaDB database. MariaDB is being considered as the future replacement free of MySQL. More information at: http://bit.ly/MARIADB

And since version 2.6 also has provided support for the CUBRID database. A management system database highly optimized for Web applications. More information at: http://bit.ly/CUBRID

The PDO4You provides an abstraction layer for data access, that regardless of which database you're using, you can always use the same methods to issue queries and fetch data.

The Singleton design pattern was adopted to optimize the connection, ensuring a single instance of the connection object.

What is the advantage in their use?

  • Instruction SQL compact using JSON notation
  • Abstraction of connection
  • Protection against SQL Injection
  • Multiple database connections
  • Methods/Commands CRUD predefined
  • Option to connect with VCAP_SERVICES
  • Error Handling with Stack Trace

Getting Started

The bootstrap file is responsible for loading the autoloader and all project dependencies. If not available, you will receive a confirmation message to start installation with Composer.

<?php

/**
 * Loads the autoloader and all project dependencies
 * The data access have been defined in the 'initial configuration file'
 */
require __DIR__.'/src/bootstrap.php';

?>

PDO4You.php: class that contains the implementation of the PDO object connection.

PDO4You.config.php: initial configuration file, server access and database.

PDO4You.settings.ini: contains the settings for each adapter of connection to the database.

Describe.php: Describe is a class used to list all the fields in a table and the data format of each field.

Pagination.php: Pagination is a class that allows you to list the records so as paged, similar to Google.

Establishing a connection to the database

To abstract our data access mechanisms, we use a DSN (Data Source Name = Data Source) that stores the information needed to initiate communication with other data sources, such as: type of technology, server name or location, database name, user, password, and other settings. This allows portability of the project, facilitating the exchange of access to the database during a migration.

<?php

// Loading all the necessary files
require __DIR__.'/src/bootstrap.php';

// Connection class imported
use PDO4You\PDO4You;


/**
 * Main ways to start a connection instance
 */

// Connection instance started and available

# DEFAULT 
PDO4You::getInstance();


// Connecting to other data sources through a DSN

# MySQL / MariaDB
PDO4You::getInstance('instance_name', 'mysql:host=localhost;dbname=pdo4you;port=3306', 'user', 'pass');

# PostgreSQL
PDO4You::getInstance('instance_name', 'pgsql:host=localhost;dbname=pdo4you;port=5432', 'user', 'pass');

# CUBRID
PDO4You::getInstance('instance_name', 'cubrid:host=localhost;dbname=pdo4you;port=33000', 'user', 'pass');

?>

Performing CRUD operations on your database

The term CRUD refers to the 4 basic operations in a database and meaning: Create(INSERT), Retrieve(SELECT), Update(UPDATE) e Destroy(DELETE)

Query statements:

PDO4You::select(): returns an array indexed by column name.

PDO4You::selectNum(): returns an array indexed by the numerical position of the column.

PDO4You::selectObj(): returns an object with column names as properties.

PDO4You::selectAll(): returns an array indexed by name and numerical position of the column.

Below are examples of how to perform these operations.

Selecting records in the database

<?php

// Loading all the necessary files
require __DIR__.'/src/bootstrap.php';

// Connection class imported
use PDO4You\PDO4You;

// Starting a connection instance. The default connection is not persistent
PDO4You::getInstance();

// Defining a persistent communication with the database
PDO4You::setPersistent(true);

// Selecting records in the database
PDO4You::select('SELECT * FROM books LIMIT 2');

// Selecting records and setting that connection instance will be used
PDO4You::select('SELECT * FROM books LIMIT 2', 'instance_name');


// Query statement
$sql = 'SELECT * FROM books LIMIT 2';

// Selecting records with PDO::FETCH_ASSOC
$result = PDO4You::select($sql);

// Selecting records with PDO::FETCH_NUM
$result = PDO4You::selectNum($sql);

// Selecting records with PDO::FETCH_OBJ
$result = PDO4You::selectObj($sql);

// Selecting records with PDO::FETCH_BOTH
$result = PDO4You::selectAll($sql);


// Selecting all records
$result = PDO4You::select('SELECT * FROM books');

// Getting the total number of rows affected by the operation
$total = PDO4You::rowCount();

// Displaying the query results
echo '<pre><h3>Query Result:</h3> ' , print_r($result, true) , '</pre>';

?>

The methods insert(), update() and delete() of the PDO4You class, are nestled between transactions, these being beginTransaction() and commit(). This ensures that the system can roll back an unsuccessful operation and all changes made ​​since the start of a transaction.

Was added in version 3.1 the execute() method, as an alternative to methods (insert, update and delete).

A serious error in the execution results in invoke rollBack(), undoing the whole operation. Consequently one Exception is thrown, tracing the path of all classes and methods involved in the operation, speeding in an environment of "production", the debug process and thus ensuring the database of the risk becoming unstable.

In MySQL, transaction support is available for InnoDB type tables.

The SQL statements of the PDO4You class (insert, update and delete) are now using JSON notation, a new format to write queries which in turn has conventions very similar to languages ​​like Python, Ruby, C++, Java, JavaScript. The new syntax adopted by the class is much more beautiful and concise, than the used by Arrays. Besides compact, instructions are capable of operating simultaneously in different tables in the same database.

Below are excerpts from example in practice.

Inserting a single row in the database

<?php

// SQL insert in JSON format
$json = '
	insert : [
		{
			table: "users" ,
			values: { mail: "[email protected]" }
		}
	] 
';

// The $result variable stores as return of the method, an array with the number of rows affected by the insert operation
$result = PDO4You::execute($json);

// Just after insertion, use the method PDO4You::lastId() to get the ID of the last insert operation in the database
$lastInsertId = PDO4You::lastId();

// If needed, enter the name of the sequence variable, required in some databases
$lastInsertId = PDO4You::lastId('table_id_seq');

?>

Inserting multiple records

<?php

// SQL insert in JSON format
$json = '
	insert : [
		{
			table: "users" ,
			values: { mail: "[email protected]" }
		},{
			table: "users" ,
			values: { mail: "[email protected]" }
		},{
			table: "books" ,
			values: { title: "title", author: "author" }
		}
	] 
';

// The $result variable stores an array with the number of rows affected by the insert operation
$result = PDO4You::execute($json);

?>

Updating multiple records

<?php

// SQL update in JSON format
$json = '
	update : [
		{
			table: "users" ,
			values: { mail: "[email protected]" } ,
			where: { id: 2 }
		},{
			table: "users" ,
			values: { mail: "[email protected]" } ,
			where: { id: 3 }
		},{
			table: "books" ,
			values: { title: "new-title", author: "new-author" } ,
			where: { id: 1 }
		}
	] 
';

// The $result variable stores an array with the number of rows affected by the update operation
$result = PDO4You::execute($json);

?>

Deleting multiple records

<?php

// SQL delete in JSON format
$json = '
	delete : [
		{
			table: "users" ,
			where: { id: 2 }
		},{
			table: "users" ,
			where: { id: 5 }
		},{
			table: "users" ,
			where: { id: 10 }
		},{
			table: "books" ,
			where: { id: 10 }
		}
	] 
';

// The $result variable stores an array with the number of rows affected by the delete operation
$result = PDO4You::execute($json);

?>

Drivers supported by the server

Execute the method below to check if the server supports a PDO driver specific to your database. Supported drivers will be displayed on the screen.

<?php

// The method below shows all the drivers installed and that are supported by the server
PDO4You::showAvailableDrivers();

?>

To enable any driver not installed, locate the php.ini file, open it and look for "extension=" without quotes, then uncomment the following lines according to your database preferably, removing the beginning of each line the "semicolon" and after changes, restart the server.

;extension=php_pdo.dll                  ; This DLL is not required as of PHP 5.3
extension=php_pdo_mysql.dll             ; MySQL 3.x/4.x/5.x / MariaDB
extension=php_pdo_pgsql.dll             ; PostgreSQL
;extension=php_pdo_cubrid.dll           ; CUBRID
;extension=php_pdo_oci.dll              ; Oracle Call Interface
;extension=php_pdo_sqlsrv.dll           ; Microsoft SQL Server / SQL Azure
;extension=php_pdo_dblib.dll            ; Microsoft SQL Server / Sybase / FreeTDS
;extension=php_pdo_mssql.dll            ; Microsoft SQL Server "Old version"
;extension=php_pdo_sqlite.dll           ; SQLite 2/3

PDO drivers for the server Xampp:
CUBRID (PHP 5.4): http://bit.ly/PDO_CUBRID-PHP54
CUBRID (PHP 5.3): http://bit.ly/PDO_CUBRID-PHP53
MS SQL Server 3.0 (PHP 5.4): http://bit.ly/PDO_SQLSRV-PHP54
MS SQL Server 2.0 (PHP 5.2/5.3): http://bit.ly/PDO_SQLSRV-PHP53
MS SQL Server (Old version): http://bit.ly/PDO_MSSQL-PHP53

Dependencies

PHP >= 5.3.2
PHPUnit >= 3.7.0 (needed to run the test suite)

Collaborators

Giovanni Ramos - [email protected] - http://twitter.com/giovanni_ramos
See also the list of colaboradores who participated in this project.

License

Copyright (c) 2010-2013 Giovanni Ramos

PDO4You is open-sourced software licensed under the MIT License

Bitdeli Badge

pdo4you's People

Contributors

giovanniramos avatar luizfonseca 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

Watchers

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

pdo4you's Issues

Dúvida sobre falha

Olá Giovanni, tudo bem?
Estou tentando usar a sua biblioteca mas estou enfrentando o seguinte problema:
Fatal error: Call to a member function getAttribute() on a non-object in C:\PHPServer\Apache2.2\htdocs\PDO4You\src\PDO4You\PDO4You.php on line 506

Não sou muito experiente com o php, mas estou tentando aprender.
Agradeço se puder me ajudar.
Um abraço. Marcel.

Undefined offset && Exception: The query is poorly formatted JSON provided.

With this json:

{"query": [
    {
        "table": "el",
        "values": {
            "birthday": null,
            "country": null,
            "first_name": "aaaa",
            "last_name": "aaa",
            "gender": null,
            "email": "[email protected]",
            "invited_friends": null,
            "newsletter": false
        }
    }
]}

I get those error messages:

Notice: Undefined offset: 1 in E:\projekte\el\app\php\db\pdo4you\pdo4you\PDO4You.class.php on line 981
 Exception: The query is poorly formatted JSON provided.
#0 E:\projekte\el\app\php\db\pdo4you\pdo4you\PDO4You.class.php:754
752
753                try {
754                    $jarr = self::parseJSON($json);
755
756                    if ($type == 'insert') {
#1 E:\projekte\el\app\php\db\pdo4you\pdo4you\PDO4You.class.php:883
881    public static function insert($json, $use = null)
882    {
883        return self::executeQuery($json, 'insert', $use);
884    }
885
#2 E:\projekte\el\app\php\postData.php:69
67    $sInitDB = 'mysql:host=' . $dbCfg['host'] . ';dbname=' . $dbCfg['db_name'] . ';port=3306';
68    PDO4You::getInstance('mysql', $sInitDB, $dbCfg['usr'], $dbCfg['pwd']);
69    $result = PDO4You::insert(json_encode($postData));
70    print $result;

I also wonder, why the local paths are shown, as the page is opened via xampp.

PostgreSQL

Para que a classe funcione no Postgre tive que comentar algumas linhas, segue:

142 = //self::$instance[$alias]->exec('SET CHARACTER SET utf8');
143 = //self::$instance[$alias]->exec('SET LC_TIME_NAMES = "pt_BR"');
200 = //self::$handle->exec("USE ".self::$database);

Redundâncias

Vendo os exemplos, e notando o mesmo molde, gostaria de propor uma sugestão:

<?php
$sql = '
{
    query : [
        {
            table: "users" ,
            values: { mail: "[email protected]" }
        }
    ] 
}
';

// A variável $result armazena, como retorno do método, um array com o ID de cada operação de inserção
$result = PDO4You::insert($sql);
?>

Para cada query que desejemos executar, temos que inserir o mesmo padrão: "query : [{ table: "users", values: "etc"}] e depois executar uma operação própria como ::insert($sql), ::delete($sql) e assim por diante.

Proponho as seguintes modificações:

  • Mudar o formato da sql para atender operações em específico, por exemplo:
<?php
$sql = '
{
    insert : [
        {
            table: "users" ,
            values: { mail: "[email protected]" }
        }
    ] 
}
';

// A variável $result armazena, como retorno do método, um array com o ID de cada operação de inserção
$result = PDO4You::execute($sql);
?>

Note a alteração no formato:

  • ao invés de "query" mudamos para a operação que queremos executar.
  • executar agora se prende somente à um método: ::execute($sql)

Assim evitamos duplicação e redundância de lógica (pelo menos em minha visão). Se concordar, remeterei um pull request com as modificações necessárias (e "enxugamento" de alguns métodos).

Sugestão

Olá,

Gostei muito do seu projeto.

Gostaria de sugerir a adição de uma function para a paginação dos resultados já integrada ao sistema com a opção de paginação tanto em GET como em POST.

Aguardo o retorno, obrigado.

"Failed communication with the database using"

Hello

I get this error with this codes:

<?php

include  __DIR__.'/src/PDO4You/PDO4You.php'; 
use PDO4You\PDO4You;
PDO4You::getInstance('instance_name', 'mysql:host=localhost;dbname=mo***;port=3306', 'mo***', 'caw***');

$result = PDO4You::select('SELECT * FROM userxw');
echo '<pre><h3>Query Result:</h3> ' , print_r($result, true) , '</pre>';

?>

Errorr
screenshot-test3 moverals com 2016-10-06 23-02-52

Where am I doing mistake?

[sugestão] Json com chaves entre aspas

Sugiro uma modificação.
Aceitar json com chaves entre aspas

exemplo:

$json =
{
"insert" :
[{
"insert": "post_rate" ,
"values": {
"id_post": 1841,
"id_user": 1,
"rate": 1,
"comment": "string entre asaps",
}
}]
};

assim ficaria facil de usarmos o json_encode por exemplo desta maneira:

$array["insert"]...;
json_encode($array);

com isso teria infinistas possibilidades de converte um array em json gerando arrays dentro laços de repetição, ou milhares de outras maneiras

Adição indesejada de caracteres em dados a serem gravados.

O método parseJSON acaba gerando um erro mesmo em JSONs válidos como esse:
{
"query": [
{
"table": "teste",
"values": {
"Dado": "{stringqualquer:"
}
}
]
}

Mesmo que isso esteja em dados que se queira gravar e sendo válido, ele acrescenta um par de aspas duplas em torno da string: {"S": fazendo a função json_decode não processar o dado por causa das aspas não escapadas.
Se bem que pode-se tirar essa combinação antes de enviar, mesmo assim, acho que isso não funciona como o esperado.

-noob :|

Campos com carecteres acentuados

Em campos com caracteres acentuados no banco de dados o PDO4You está retornando NULL como se na tabela do banco de dados o campos estivesse realmente vazio.

Possivel problema na filtragem de caracteres

Um problema que percebi foi que caracteres UTF-8 na faixa dos emoji U+1F600 até U+1F6FF

Ou seja quando os envio eles chegam no php mas na hora de gravar no banco via PDO4You ele simplesmente desaparece ou é truncado (??);

Outro erro foi quando enviei : (dois pontos). ele retorna que o json está mal formado.

Existe solução para o caso ?

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.