php pdo class github
Php pdo class github
A PHP MySQL PDO class similar to the Python MySQLdb, which supports iterator and parameter binding when using «WHERE IN» statement.
Copy the files under src/ to your program
Preventing SQL Injection Attacks
Safety: Use parameter binding method
Unsafety: Split joint SQL string
id | name | color |
---|---|---|
1 | apple | red |
2 | banana | yellow |
3 | watermelon | green |
4 | pear | yellow |
5 | strawberry | red |
Fetching with Bindings (ANTI-SQL-INJECTION):
WHERE IN (needs named placeholder):
Delete / Update / Insert
These operations will return the number of affected result set. (integer)
Get Last Insert ID
Get the number of queries since the object initialization
Use iterator when you want to read thousands of data from the database for statistical or full update of Elastic Search or Solr indexes.
Iterator is a traversable object that does not read all the data queried from MySQL into memory.
So you can safely use foreach to handle millions of MySQL result sets without worrying about excessive memory usage.
About
A PHP MySQL PDO class similar to the the Python MySQLdb, which supports iterator and parameter binding when using «WHERE IN» statement.
Php pdo class github
Безопасный и простой PDO класс для работы с базой данных. Русская документация.
PHP: PDO Db Wrapper with prepared statements
Смотрите Английскую документацию чтобы получить больше информации
Вернуться назад на главную страницу
Installation
Initialization
Select
Select Join
Insert
Insert Multiple
Last Insert Id
Update
Delete
Create Database
Create Table
Optimize Table
Truncate Table
Drop Database
Drop Table
или же вы можете использовать автозагрузку:
Простая инициализация: создаем подключение к базе с кодировкой utf8 по умолчанию:
выбираем все из таблицы table1
выбираем 1 строку из таблицы table1 где id == 1
выбираем колонки col1 и col2 из таблицы table1
выбираем колонки col1 и col2 из таблицы table1 с лимтом от 0 до 3 с сортировкой по возростанию
выбираем данные из таблиц articles, authors, tags
во избежание конфликтов для колонок id и title задаем псевдонимы
вставка строки в таблицу table1 с колонками id, title, content
метод возвращает последний id запроса, что был выполнен ранее
обновление колонки col1 в таблице table1
обновление всех колонок col1 в таблице table1 где значение == Заголовок № 10
Php pdo class github
PHP PDO Wrapper which utilizes PDO and prepared statements
This software is developed during my free time and I will be glad if somebody will support me.
Everyone’s time should be valuable, so please consider donating.
To utilize this class, first import PDODb.php into your project, and require it. PDODb requires PHP 5.5+ to work.
Installation with composer
It is also possible to install library via composer
Simple initialization with utf8 charset set by default:
table prefix, port and database charset params are optional. If no charset should be set charset, set it to null
Also it is possible to reuse already connected pdo object:
If no table prefix were set during object creation its possible to set it later with a separate call:
If you need to get already created pdo object from another class or function use
Insert with functions use
Insert with on duplicate key update
Replace() method implements same API as insert();
update() also support limit parameter:
or select with custom columns set. Functions also could be used
or select just one row
or select one column value or function result
select one column value or function result from multiple rows:
You may use php 5.5+ generator feature with PDODb get(), rawQuery() methods just call useGenerator(true) method
Use paginate() instead of get() to fetch paginated result
Defining a return type
To select a return type use setReturnType() method.
Running raw SQL queries
To avoid long if checks there are couple helper functions to work with raw query select results:
Get 1 row of results:
Get 1 column value as a string:
Get 1 column value from multiple rows:
More advanced examples:
Where / Having Methods
WARNING: In order to use column to column comparisons only raw where conditions should be used as column name or functions cant be passed as a bind variable.
Regular == operator with variables:
Regular == operator with column to column comparison:
BETWEEN / NOT BETWEEN:
Also you can use raw where conditions:
Or raw condition with variables:
Find the total number of rows matched. Simple pagination example:
To add LOW PRIORITY | DELAYED | HIGH PRIORITY | IGNORE and the rest of the mysql keywords to INSERT (), REPLACE (), GET (), UPDATE (), DELETE() method or FOR UPDATE | LOCK IN SHARE MODE into SELECT ():
Also you can use an array of keywords:
Same way keywords could be used in SELECT queries as well:
Optionally you can use method chaining to call where multiple times without referencing your object over an over:
Order by values example:
If you are using setPrefix () functionality and need to use table names in orderBy() method make sure that table names are escaped with «.
Join table products with table users with LEFT JOIN by tenantID
Its is also possible to copy properties
Subquery init without an alias to use in inserts/updates/where Eg. (select * from users)
Subquery in selects:
Subquery in inserts:
EXISTS / NOT EXISTS condition
A convenient function that returns TRUE if exists at least an element that satisfy the where condition specified calling the «where» method before this one.
Get last executed SQL query: Please note that function returns SQL query only for debugging purposes as its execution most likely will fail due missing quotes around char variables.
Check if table exists:
Please keep in mind that transactions are working on innoDB tables. Rollback transaction if insert fails:
After you executed a query you have options to check if there was an error. You can get the MySQL error string or the error code for the last executed query.
About
PHP PDO Wrapper which utilizes PDO and prepared statements
Php pdo class github
This model will handle your typical database communication using PDO.
The methods in this model typically takes an array of ‘column’ => ‘value’, making it possible to pass along several clauses to an query.
I.e. it is possible to define several WHERE, ORDER & JOIN clauses in the same array.
This model will prepare the values, before performing the query.
BE AWARE THOUGH! Not everything passed to this model, will be escaped.
As a rule of thumb only the VALUES are being escaped, and NOT the COLUMN(s)!
In the following examples (Create, Read, Update & Delete) all the example-values marked with a start (*) will be escaped.
Column & Value Explained
To create a new record in the database.
Insert into several columns
Read one, or more, record(s) from the database.
The first value in the array is the LIMIT, the second value in the array is the OFFSET. Both values must be a positive numeric.
The 5th parameter is for building JOIN clauses.
BE AWARE! That the JOIN and ON clauses are currently not being escaped.
A typical JOIN query could look something like this:
With that in mind, the JOIN array is a little special. First, define the ON clause, then define which JOIN (LEFT, RIGHT etc) to which table.
You are able to define several JOIN & ON clauses.
Update a record in the database.
Delete a record from the database.
If you have a query that doesn’t quite fit into one of the above CRUD methods, a method for performing PDO queries is also available.
It will take a SQL string and execute it against the database. It is possible to use prepared statements with this method as well!
An example could i.e. be the use of the COUNT function (Though, this could be done with the READ method).
If you’re expecting a return from your query, a 3th parameter should be set to ‘true’. It is not every query that will return a value, so it has to be actively set when needed.
This model also holds a ‘debug’ method. If you’re in doubt how you SQL string is looking, call the method before making the query.
This will stop the model from making the query, and instead return an array with the SQL string and the prepared values.
If the debug() method is called before the query ( read() i.e.), then the following will be output, instead of running the query:
About
PHP PDO connection with Create, Read, Update and Delete (CRUD) class.
Php pdo class github
A forked version of PHP-PDO-MySQL-Class to work with SQL Server.
Copy the files under src/ to your program
Preventing SQL Injection Attacks
Safety: Use parameter binding method
Unsafety: Split joint SQL string
id | name | color |
---|---|---|
1 | apple | red |
2 | banana | yellow |
3 | watermelon | green |
4 | pear | yellow |
5 | strawberry | red |
Fetching with Bindings (ANTI-SQL-INJECTION):
WHERE IN (needs named placeholder):
Delete / Update / Insert
These operations will return the number of affected result set. (integer)
Get Last Insert ID
Get the number of queries since the object initialization
Use iterator when you want to read thousands of data from the database for statistical or full update of Elastic Search or Solr indexes.
Iterator is a traversable object that does not read all the data queried from MySQL into memory.
So you can safely use foreach to handle millions of MySQL result sets without worrying about excessive memory usage.
About
A PHP MsSQL PDO class similar to the the Python MySQLdb, which supports iterator and parameter binding when using «WHERE IN» statement.