• Stars
    star
    243
  • Rank 166,489 (Top 4 %)
  • Language
    PHP
  • License
    Apache License 2.0
  • Created about 10 years ago
  • Updated almost 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A PHP MySQL PDO class similar to the the Python MySQLdb, which supports iterator and parameter binding when using "WHERE IN" statement.

PHP-PDO-MySQL-Class Build Status

A PHP MySQL PDO class similar to the Python MySQLdb, which supports iterator and parameter binding when using "WHERE IN" statement.

Install

Copy the files under src/ to your program

OR

composer require lincanbin/php-pdo-mysql-class

Initialize

<?php
define('DBHost', '127.0.0.1');
define('DBPort', 3306);
define('DBName', 'Database');
define('DBUser', 'root');
define('DBPassword', '');
require(__DIR__ . "/src/PDO.class.php");
$DB = new Db(DBHost, DBPort, DBName, DBUser, DBPassword);
?>

Preventing SQL Injection Attacks

Safety: Use parameter binding method

Safety Example:

<?php
$DB->query("SELECT * FROM fruit WHERE name=?", array($_GET['name']));
?>

Unsafety: Split joint SQL string

Unsafety Example:

<?php
$DB->query("SELECT * FROM fruit WHERE name=".$_GET['name']);
?>

Basic Usage

table "fruit"

id name color
1 apple red
2 banana yellow
3 watermelon green
4 pear yellow
5 strawberry red

Fetching with Bindings (ANTI-SQL-INJECTION):

<?php
$DB->query("SELECT * FROM fruit WHERE name=? and color=?",array('apple','red'));
$DB->query("SELECT * FROM fruit WHERE name=:name and color=:color",array('name'=>'apple','color'=>'red'));
?>

Result:

Array
(
	[0] => Array
		(
			[id] => 1
			[name] => apple
			[color] => red
		)
)

WHERE IN (needs named placeholder):

<?php
$DB->query("SELECT * FROM fruit WHERE name IN (:fruits)",array(array('apple','banana')));
?>

Result:

Array
(
	[0] => Array
		(
			[id] => 1
			[name] => apple
			[color] => red
		)
	[1] => Array
		(
			[id] => 2
			[name] => banana
			[color] => yellow
		)
)
<?php
$query = "SELECT * FROM fruit WHERE name IN (:fruits) AND color = :color";
// use multidimensional array as $params
$params = array(
	"color" => "red",
	"fruits" => array(
		"apple",
		"banana"
	)
);
$DB->query($query, $params);
?>

Result:

Array
(
	[0] => Array
		(
			[id] => 1
			[name] => apple
			[color] => red
		)
)

Fetching Column:

<?php
$DB->column("SELECT color FROM fruit WHERE name IN (:color)",array('apple','banana','watermelon'));
?>

Result:

Array
(
	[0] => red
	[1] => yellow
	[2] => green
)

Fetching Row:

<?php
$DB->row("SELECT * FROM fruit WHERE name=? and color=?",array('apple','red'));
?>

Result:

Array
(
	[id] => 1
	[name] => apple
	[color] => red
)

Fetching single:

<?php
$DB->single("SELECT color FROM fruit WHERE name=? ",array('watermelon'));
?>

Result:

green

Delete / Update / Insert

These operations will return the number of affected result set. (integer)

<?php
// Delete
$DB->query("DELETE FROM fruit WHERE id = :id", array("id"=>"1"));
$DB->query("DELETE FROM fruit WHERE id = ?", array("1"));
// Update
$DB->query("UPDATE fruit SET color = :color WHERE name = :name", array("name"=>"strawberry","color"=>"yellow"));
$DB->query("UPDATE fruit SET color = ? WHERE name = ?", array("yellow","strawberry"));
// Insert
$DB->query("INSERT INTO fruit(id,name,color) VALUES(?,?,?)", array(null,"mango","yellow"));//Parameters must be ordered
$DB->query("INSERT INTO fruit(id,name,color) VALUES(:id,:name,:color)", array("color"=>"yellow","name"=>"mango","id"=>null));//Parameters order free
?>

Get Last Insert ID

<?php
$DB->lastInsertId();
?>

Get the number of queries since the object initialization

<?php
$DB->querycount;
?>

Close Connection

<?php
$DB->closeConnection();
?>

Transaction

<?php
try {
    $DB->beginTransaction();
    var_dump($DB->inTransaction()); // print "true"
    $DB->commit();
} catch(Exception $ex) {
    // handle Error
    $DB->rollBack();
}
?>

Iterator

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.

Example:

$iteratorInstance = $DB->iterator("SELECT * FROM fruit limit 0, 1000000;");
$colorCountMap = array(
    'red' => 0,
    'yellow' => 0,
    'green' => 0
);
foreach($iteratorInstance as $key => $value) {
    sendDataToElasticSearch($key, $value);
    $colorCountMap[$value['color']]++;
}
var_export($colorCountMap);

Return:

array(3) {
  [red] => 2
  [yellow] => 2
  [green] => 1
}

More Repositories

1

Carbon-Forum

A high performance open-source forum software written in PHP. Discussions Tags based with Quora/StackOverflow style.
PHP
1,838
star
2

Holy-Lance

A Linux Resource / Performance Monitor based on PHP.
PHP
306
star
3

Material-Design-Avatars

Create material deisgn avatars for users just like Google Messager. It may not be unique but looks better than Identicon or Gravatar.
PHP
264
star
4

Android-Carbon-Forum

Android Client for Carbon Forum with Material Design.
Java
249
star
5

Sina-Weibo-Album-Downloader

Multithreading download all HD photos / pictures from someone's Sina Weibo album.
Python
126
star
6

Pythonic-PHP-Code-Formatter

Pythonic PHP code formatter. Just for fun.
PHP
69
star
7

Telegram-Simple-Image-Bot

A simple telegram bot which can return a random picture.
PHP
55
star
8

Carbon-Forum-API-Documentation

Carbon Forum HTTP API Documentation.
44
star
9

STM32-TEA-Encryption-Recorder

A STM32 encryption recorder that use Tiny Encryption Algorithm.
C
14
star
10

White-HTML-Filter

A lightweight php-based HTML tag and attribute whitelist filter.
PHP
12
star
11

STM32-Alarm-Clock

Keil uVision4 project of STM32 Alarm Clock.
C
9
star
12

apidoc-markdown

Generate API documentation in markdown format from API annotations in your source code.
PHP
5
star
13

Library-Management-System

PHP
4
star
14

Python-Binary-Statistics

Count the number of 1 and 0 in a binary file.
Python
4
star
15

Arduino-Location-Based-Environment-Detector-Client

Arduino Client of Location Based Environment Detector.
C++
4
star
16

Arduino-Location-Based-Environment-Detector-PC-Client

Arduino Location Based Environment Detector PC Client. This tool is used for debugging in the case that SIM900 is not working.
Python
3
star
17

PHP-Image-Resize-Class

Automatic extract the square central part of the uploaded image, and zoom to the specified size.
PHP
3
star
18

Theseus-Templates

PHP
2
star
19

iOS-Carbon-Forum

iOS Client for Carbon Forum.
Swift
2
star
20

Arduino-Location-Based-Environment-Detector-Server

PHP Server Script of Location Based Environment Detector.
PHP
2
star
21

Thunder-Link-Parser

1
star
22

go-time-clock

1
star
23

VHDL-74LS160

Quartus 9.0 Project of 74LS160.
VHDL
1
star
24

VHDL-Frequency-Divider

Quartus 9.0 Project of Frequency Divider.
VHDL
1
star