Giter VIP home page Giter VIP logo

php-pdo-mysql-class's Introduction

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
}

php-pdo-mysql-class's People

Contributors

altmas5 avatar catruzz avatar jjasoncool avatar k00ni avatar lincanbin avatar merong 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

php-pdo-mysql-class's Issues

feat: 2020/07/21 Add Log parameter info

Just a little suggestion

PDO.class.php @345

        // add query parameters info, because using prepared statement can't view parameters logs
        if (isset($parameters['parameters'])) {
            $message .= "\r\nParamters : " . print_r($parameters['parameters'], true);
        }

DESCRIBE TABLE not working

I used this code snippet to get the column names $result = $DB->query('DESCRIBE '.$table);
Did not work, tyried different ways, no luck.
I changed something in the class to get it to work, I added inside the function query($query, $params = null, $fetchMode = PDO::FETCH_ASSOC) a extra statement.
if ($statement === 'select' || $statement === 'show' || $statement === 'describe')
Now it works and my function will return either a form, list or just the names.
Maybe to consider for the next update in the class to add this extra statement?

Very nice class, love it.
A good job well done is half the worries. -;)

Statement Success Or Not

how can i determine query are success or not ?
some like if ($execute = DB->query(blablabla)){} ?

UPDATE not working for WHERE x IN() statement

The IN statement for UPDATE seems to be interpreted wrong. It only executes for the first value:

$result= $this->DB->query("UPDATE table SET column=0 WHERE id IN (?)",array( "1, 3, 5, 6"));
This only sets column for the id=1, but there are rows with id 3,5 or 6

Otherwise the SELECT statement is working:
$result= $this->DB->query("SELECT column FROM table WHERE id IN (?)",array( "1, 3, 5, 6"));
This gets all rows of column for the selected IDs.

Do I miss something or is it a bug?

Added call method

Maybe someone could find it interesting ...

public function call($query, $params = null, $fetchmode = PDO::FETCH_ASSOC)
{
$this->Init($query, $params);
$result = $this->sQuery->fetchAll($fetchmode);
$this->sQuery->nextRowset();
return $result;
}

Bind in human readable way

I would suggest you add binding paramters in a more readable way. e.g

$db->bind('par1',  'xyz' );
$db->bind('par2',  'abc' );
$db->query('SELECT *
FROM table1
WHERE table1.a = :par1 AND table1.b = :par2 ');

How would we use UNION or JOINS in SELECT queries?

I'm looking to run a union query, here's what I've got:

$get_posts = $DB->query( "SELECT * FROM op_posts WHERE post_author_id IN (:ids) UNION SELECT * FROM op_post_shares WHERE share_user_id IN (:ids)", array('ids' => array(1, 2, 54)) );

But it spits out the error:
Cardinality violation: 1222 The used SELECT statements have a different number of columns

OR with the same value

My problem is that i will check is value x in the column a or b exist.
How I can do this?

I get: SQLSTATE[HY093]: Invalid parameter number: parameter was not defined

I tried:
$DB->query("SELECT * FROM accounting_entries WHERE soll=:nr OR haben=:nr", array('nr'=>$this->nr));

about where in

SELECT * FROM fruit WHERE name IN (apple','banana) AND color = 'red'
how to add "red" ?
$DB->query("SELECT * FROM fruit WHERE name IN (?) AND color = ? ",array('apple','banana'));

Problem with charset UTF8

Hi, how can i set utf8?

Work nice this library, however some rows give me this: restricción de movilidad por cédula y género en Panamá

In PDO is used SET NAMES UTF8, but in this library what should I use?

How to turn off logs?

I want to turn off logs, as I don't really want to be accessing this from the front end of my website.

How do I do this?

INSERT or UPDATE if exists

There is a need to INSERT or UPDATE values if they exist.

INSERT INTO TABLE (id, name, age) VALUES (1, "A", 19), (2, "B", 17), (3, "C", 22)
ON DUPLICATE KEY UPDATE
    age = 20;

Inserts multiple rows in single query

This opportunity is missing:
INSERT INTO tbl (key1, key2) VALUES ('r1v1', 'r1v2'),('r2v1', 'r2v2'),...
I tried to create an array but get a PHP error.

$params=[];
$params[] = ["key1" => "value1", "key2 => "value2_1"];
$params[] = ["key1" => "value2", "key2 => "value2_2"];
$params[] = ["key1" => "value3", "key2 => "value2_3"];
$DB->query($query, $params);```

> PHP Fatal error:  Uncaught ValueError: PDOStatement::bindParam(): Argument #1 ($param) must be greater than or equal to 1 in /lincanbin/php-pdo-mysql-class/src/PDO.class.php:137

like is not work

PHP>=5.4
$db->query("select * from item where cc like '%,?,%'",[$aid]);
error log:SQLSTATE[42000]: Syntax error or access violation: 1065 Query was empty

Hello

Please change this

	if ($statement === 'select' || $statement === 'show' || $statement === 'call' || $statement === 'describe') {
		$fetchReturn = $this->sQuery->fetchAll($fetchMode);
		$this->sQuery->closeCursor();
		return $fetchReturn;
	} elseif ($statement === 'insert' || $statement === 'update' || $statement === 'delete') {
		return $this->sQuery->rowCount();
	} else {
		return NULL;
	}

Log path

These small changes would be nice to add to the repo, so that the log path can be changed.

PDO.class.php
public function __construct($Host, $DBPort, $DBName, $DBUser, $DBPassword, $LogPath = '')
{
$this->logObject = new PDOLog($LogPath);

PDO.Log.class.php
public function __construct($LogPath = '')
{
if (empty($LogPath)) $this->path = DIR . $this->path;
else $this->path = $LogPath;
}

For updates where newvalue = oldvalue, PDOStatement::rowCount() returns zero

When init PDO then add an option (PDO::MYSQL_ATTR_FOUND_ROWS => true) to disable this unexpected behaviour.

Ex:
$this->pdo = new PDO($dsn,
$this->DBUser,
$this->DBPassword,
array(
//For PHP 5.3.6 or lower
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8",
PDO::ATTR_EMULATE_PREPARES => false,

	//长连接
	//PDO::ATTR_PERSISTENT => true,
	
	PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
	PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true,
	PDO::MYSQL_ATTR_FOUND_ROWS => true //Here
)

);

Using define to input database credentials and also making them public

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

Why can't use ini file that puts credentials to main db function and link with main db php class, which won't require parameters to be required everytime. Just execute db() and go.

PDO.class.php broken ?

i was using old version of PDO.class.php , just copied fresh copy of PDO.class.php and replaced my old one with it , and noticed i started getting 500 error. then reverted back .

please check

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.