Repository: indieteq/indieteq-php-my-sql-pdo-database-class
Branch: master
Commit: 72eb816e4cff
Files: 11
Total size: 28.1 KB
Directory structure:
gitextract_d3ec_8g3/
├── Db.class.php
├── LICENSE
├── Log.class.php
├── README.md
├── SQL dump/
│ └── testdb.sql
├── composer.json
├── easyCRUD/
│ ├── Person.class.php
│ ├── easyCRUD.class.php
│ └── index.php
├── index.php
└── settings.ini.php
================================================
FILE CONTENTS
================================================
================================================
FILE: Db.class.php
================================================
<?php
/**
* DB - A simple database class
*
* @author Author: Vivek Wicky Aswal. (https://twitter.com/#!/VivekWickyAswal)
* @git https://github.com/wickyaswal/PHP-MySQL-PDO-Database-Class
* @version 0.2ab
*
*/
require("Log.class.php");
class DB
{
# @object, The PDO object
private $pdo;
# @object, PDO statement object
private $sQuery;
# @array, The database settings
private $settings;
# @bool , Connected to the database
private $bConnected = false;
# @object, Object for logging exceptions
private $log;
# @array, The parameters of the SQL query
private $parameters;
/**
* Default Constructor
*
* 1. Instantiate Log class.
* 2. Connect to database.
* 3. Creates the parameter array.
*/
public function __construct()
{
$this->log = new Log();
$this->Connect();
$this->parameters = array();
}
/**
* This method makes connection to the database.
*
* 1. Reads the database settings from a ini file.
* 2. Puts the ini content into the settings array.
* 3. Tries to connect to the database.
* 4. If connection failed, exception is displayed and a log file gets created.
*/
private function Connect()
{
$this->settings = parse_ini_file("settings.ini.php");
$dsn = 'mysql:dbname=' . $this->settings["dbname"] . ';host=' . $this->settings["host"] . '';
try {
# Read settings from INI file, set UTF8
$this->pdo = new PDO($dsn, $this->settings["user"], $this->settings["password"], array(
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"
));
# We can now log any exceptions on Fatal error.
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
# Disable emulation of prepared statements, use REAL prepared statements instead.
$this->pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
# Connection succeeded, set the boolean to true.
$this->bConnected = true;
}
catch (PDOException $e) {
# Write into log
echo $this->ExceptionLog($e->getMessage());
die();
}
}
/*
* You can use this little method if you want to close the PDO connection
*
*/
public function CloseConnection()
{
# Set the PDO object to null to close the connection
# http://www.php.net/manual/en/pdo.connections.php
$this->pdo = null;
}
/**
* Every method which needs to execute a SQL query uses this method.
*
* 1. If not connected, connect to the database.
* 2. Prepare Query.
* 3. Parameterize Query.
* 4. Execute Query.
* 5. On exception : Write Exception into the log + SQL query.
* 6. Reset the Parameters.
*/
private function Init($query, $parameters = "")
{
# Connect to database
if (!$this->bConnected) {
$this->Connect();
}
try {
# Prepare query
$this->sQuery = $this->pdo->prepare($query);
# Add parameters to the parameter array
$this->bindMore($parameters);
# Bind parameters
if (!empty($this->parameters)) {
foreach ($this->parameters as $param => $value) {
if(is_int($value[1])) {
$type = PDO::PARAM_INT;
} else if(is_bool($value[1])) {
$type = PDO::PARAM_BOOL;
} else if(is_null($value[1])) {
$type = PDO::PARAM_NULL;
} else {
$type = PDO::PARAM_STR;
}
// Add type when binding the values to the column
$this->sQuery->bindValue($value[0], $value[1], $type);
}
}
# Execute SQL
$this->sQuery->execute();
}
catch (PDOException $e) {
# Write into log and display Exception
echo $this->ExceptionLog($e->getMessage(), $query);
die();
}
# Reset the parameters
$this->parameters = array();
}
/**
* @void
*
* Add the parameter to the parameter array
* @param string $para
* @param string $value
*/
public function bind($para, $value)
{
$this->parameters[sizeof($this->parameters)] = [":" . $para , $value];
}
/**
* @void
*
* Add more parameters to the parameter array
* @param array $parray
*/
public function bindMore($parray)
{
if (empty($this->parameters) && is_array($parray)) {
$columns = array_keys($parray);
foreach ($columns as $i => &$column) {
$this->bind($column, $parray[$column]);
}
}
}
/**
* If the SQL query contains a SELECT or SHOW statement it returns an array containing all of the result set row
* If the SQL statement is a DELETE, INSERT, or UPDATE statement it returns the number of affected rows
*
* @param string $query
* @param array $params
* @param int $fetchmode
* @return mixed
*/
public function query($query, $params = null, $fetchmode = PDO::FETCH_ASSOC)
{
$query = trim(str_replace("\r", " ", $query));
$this->Init($query, $params);
$rawStatement = explode(" ", preg_replace("/\s+|\t+|\n+/", " ", $query));
# Which SQL statement is used
$statement = strtolower($rawStatement[0]);
if ($statement === 'select' || $statement === 'show') {
return $this->sQuery->fetchAll($fetchmode);
} elseif ($statement === 'insert' || $statement === 'update' || $statement === 'delete') {
return $this->sQuery->rowCount();
} else {
return NULL;
}
}
/**
* Returns the last inserted id.
* @return string
*/
public function lastInsertId()
{
return $this->pdo->lastInsertId();
}
/**
* Starts the transaction
* @return boolean, true on success or false on failure
*/
public function beginTransaction()
{
return $this->pdo->beginTransaction();
}
/**
* Execute Transaction
* @return boolean, true on success or false on failure
*/
public function executeTransaction()
{
return $this->pdo->commit();
}
/**
* Rollback of Transaction
* @return boolean, true on success or false on failure
*/
public function rollBack()
{
return $this->pdo->rollBack();
}
/**
* Returns an array which represents a column from the result set
*
* @param string $query
* @param array $params
* @return array
*/
public function column($query, $params = null)
{
$this->Init($query, $params);
$Columns = $this->sQuery->fetchAll(PDO::FETCH_NUM);
$column = null;
foreach ($Columns as $cells) {
$column[] = $cells[0];
}
return $column;
}
/**
* Returns an array which represents a row from the result set
*
* @param string $query
* @param array $params
* @param int $fetchmode
* @return array
*/
public function row($query, $params = null, $fetchmode = PDO::FETCH_ASSOC)
{
$this->Init($query, $params);
$result = $this->sQuery->fetch($fetchmode);
$this->sQuery->closeCursor(); // Frees up the connection to the server so that other SQL statements may be issued,
return $result;
}
/**
* Returns the value of one single field/column
*
* @param string $query
* @param array $params
* @return string
*/
public function single($query, $params = null)
{
$this->Init($query, $params);
$result = $this->sQuery->fetchColumn();
$this->sQuery->closeCursor(); // Frees up the connection to the server so that other SQL statements may be issued
return $result;
}
/**
* Writes the log and returns the exception
*
* @param string $message
* @param string $sql
* @return string
*/
private function ExceptionLog($message, $sql = "")
{
$exception = 'Unhandled Exception. <br />';
$exception .= $message;
$exception .= "<br /> You can find the error back in the log.";
if (!empty($sql)) {
# Add the Raw SQL to the Log
$message .= "\r\nRaw SQL : " . $sql;
}
# Write into log
$this->log->write($message);
return $exception;
}
}
?>
================================================
FILE: LICENSE
================================================
/*
* ----------------------------------------------------------------------------
* "THE BEER-WARE LICENSE"
* If we meet some day, and you think
* this stuff is worth it, you can buy me a beer in return.
* ----------------------------------------------------------------------------
*/
================================================
FILE: Log.class.php
================================================
<?php
/* *
* Log A logger class which creates logs when an exception is thrown.
* @author Author: Vivek Wicky Aswal. (https://twitter.com/#!/VivekWickyAswal)
* @git https://github.com/wickyaswal/PHP-MySQL-PDO-Database-Class
* @version 0.1a
*/
class Log {
# @string, Log directory name
private $path = '/logs/';
# @void, Default Constructor, Sets the timezone and path of the log files.
public function __construct() {
date_default_timezone_set('Europe/Amsterdam');
$this->path = dirname(__FILE__) . $this->path;
}
/**
* @void
* Creates the log
*
* @param string $message the message which is written into the log.
* @description:
* 1. Checks if directory exists, if not, create one and call this method again.
* 2. Checks if log already exists.
* 3. If not, new log gets created. Log is written into the logs folder.
* 4. Logname is current date(Year - Month - Day).
* 5. If log exists, edit method called.
* 6. Edit method modifies the current log.
*/
public function write($message) {
$date = new DateTime();
$log = $this->path . $date->format('Y-m-d').".txt";
if(is_dir($this->path)) {
if(!file_exists($log)) {
$fh = fopen($log, 'a+') or die("Fatal Error !");
$logcontent = "Time : " . $date->format('H:i:s')."\r\n" . $message ."\r\n";
fwrite($fh, $logcontent);
fclose($fh);
}
else {
$this->edit($log,$date, $message);
}
}
else {
if(mkdir($this->path,0777) === true)
{
$this->write($message);
}
}
}
/**
* @void
* Gets called if log exists.
* Modifies current log and adds the message to the log.
*
* @param string $log
* @param DateTimeObject $date
* @param string $message
*/
private function edit($log,$date,$message) {
$logcontent = "Time : " . $date->format('H:i:s')."\r\n" . $message ."\r\n\r\n";
$logcontent = $logcontent . file_get_contents($log);
file_put_contents($log, $logcontent);
}
}
?>
================================================
FILE: README.md
================================================
I am not maintaining this repository anymore and I would like to request you to find a better repo or make a fork of this repository!
============================
PDO Database Class
============================
A database class for PHP-MySQL which uses the PDO extension.
## To use the class
#### 1. Edit the database settings in the settings.ini.php
### Note if PDO is loading slow change localhost to -> 127.0.0.1 !
```
[SQL]
host = 127.0.0.1
user = root
password =
dbname = yourdatabase
```
#### 2. Require the class in your project
```php
<?php
require("Db.class.php");
```
#### 3. Create the instance
```php
<?php
// The instance
$db = new Db();
```
#### 4. Logs - Modify the read/write rights of the root folder
Everytime an exception is thrown by the database class a log file gets created or modified.
These logs are stored in the logs directory. Which means the database class needs write access for the logs folder.
If the files are on a webserver you'll have to modify the rights of the root folder otherwise you'll get a "Permission denied" error.
The log file is a simple plain text file with the current date('year-month-day') as filename.
## Examples
Below some examples of the basic functions of the database class. I've included a SQL dump so you can easily test the database
class functions.
#### The persons table
| id | firstname | lastname | sex | age
|:-----------:|:------------:|:------------:|:------------:|:------------:|
| 1 | John | Doe | M | 19
| 2 | Bob | Black | M | 41
| 3 | Zoe | Chan | F | 20
| 4 | Kona | Khan | M | 14
| 5 | Kader| Khan | M | 56
#### Fetching everything from the table
```php
<?php
// Fetch whole table
$persons = $db->query("SELECT * FROM persons");
```
#### Fetching with Bindings (ANTI-SQL-INJECTION):
Binding parameters is the best way to prevent SQL injection. The class prepares your SQL query and binds the parameters
afterwards.
There are three different ways to bind parameters.
```php
<?php
// 1. Read friendly method
$db->bind("id","1");
$db->bind("firstname","John");
$person = $db->query("SELECT * FROM Persons WHERE firstname = :firstname AND id = :id");
// 2. Bind more parameters
$db->bindMore(array("firstname"=>"John","id"=>"1"));
$person = $db->query("SELECT * FROM Persons WHERE firstname = :firstname AND id = :id"));
// 3. Or just give the parameters to the method
$person = $db->query("SELECT * FROM Persons WHERE firstname = :firstname AND id = :id",array("firstname"=>"John","id"=>"1"));
```
More about SQL injection prevention : http://indieteq.com/index/readmore/how-to-prevent-sql-injection-in-php
#### Fetching Row:
This method always returns only 1 row.
```php
<?php
// Fetch a row
$ages = $db->row("SELECT * FROM Persons WHERE id = :id", array("id"=>"1"));
```
##### Result
| id | firstname | lastname | sex | age
|:-----------:|:------------:|:------------:|:------------:|:------------:|
| 1 | John | Doe | M | 19
#### Fetching Single Value:
This method returns only one single value of a record.
```php
<?php
// Fetch one single value
$db->bind("id","3");
$firstname = $db->single("SELECT firstname FROM Persons WHERE id = :id");
```
##### Result
|firstname
|:------------:
| Zoe
#### Using the like keyword
```php
<?php
// Using Like
// Notice the wildcard at the end of the value!!
$like = $db->query("SELECT * FROM Persons WHERE Firstname LIKE :firstname ", array("firstname"=>"sekit%"));
```
##### Result
| id | firstname | lastname | sex | age
|:-----------:|:------------:|:------------:|:------------:|:------------:|
| 4 | Sekito | Khan | M | 19
#### Fetching Column:
```php
<?php
// Fetch a column
$names = $db->column("SELECT Firstname FROM Persons");
```
##### Result
|firstname |
|:-----------:
| John
| Bob
| Zoe
| Kona
| Kader
### Delete / Update / Insert
When executing the delete, update, or insert statement by using the query method the affected rows will be returned.
```php
<?php
// Delete
$delete = $db->query("DELETE FROM Persons WHERE Id = :id", array("id"=>"1"));
// Update
$update = $db->query("UPDATE Persons SET firstname = :f WHERE Id = :id", array("f"=>"Jan","id"=>"32"));
// Insert
$insert = $db->query("INSERT INTO Persons(Firstname,Age) VALUES(:f,:age)", array("f"=>"Vivek","age"=>"20"));
// Do something with the data
if($insert > 0 ) {
return 'Succesfully created a new person !';
}
```
## Method parameters
Every method which executes a query has the optional parameter called bindings.
The <i>row</i> and the <i>query</i> method have a third optional parameter which is the fetch style.
The default fetch style is <i>PDO::FETCH_ASSOC</i> which returns an associative array.
Here an example :
```php
<?php
// Fetch style as third parameter
$person_num = $db->row("SELECT * FROM Persons WHERE id = :id", array("id"=>"1"), PDO::FETCH_NUM);
print_r($person_num);
// Array ( [0] => 1 [1] => Johny [2] => Doe [3] => M [4] => 19 )
```
More info about the PDO fetchstyle : http://php.net/manual/en/pdostatement.fetch.php
EasyCRUD
============================
The easyCRUD is a class which you can use to easily execute basic SQL operations like(insert, update, select, delete) on your database.
It uses the database class I've created to execute the SQL queries.
Actually it's just a little ORM class.
## How to use easyCRUD
#### 1. First, create a new class. Then require the easyCRUD class.
#### 2. Extend your class to the base class Crud and add the following fields to the class.
#### Example class :
```php
<?php
require_once("easyCRUD.class.php");
class YourClass Extends Crud {
# The table you want to perform the database actions on
protected $table = 'persons';
# Primary Key of the table
protected $pk = 'id';
}
```
## EasyCRUD in action.
#### Creating a new person
```php
<?php
// First we"ll have create the instance of the class
$person = new person();
// Create new person
$person->Firstname = "Kona";
$person->Age = "20";
$person->Sex = "F";
$created = $person->Create();
// Or give the bindings to the constructor
$person = new person(array("Firstname"=>"Kona","age"=>"20","sex"=>"F"));
$created = $person->Create();
// SQL Equivalent
"INSERT INTO persons (Firstname,Age,Sex) VALUES ('Kona','20','F')"
```
#### Deleting a person
```php
<?php
// Delete person
$person->Id = "17";
$deleted = $person->Delete();
// Shorthand method, give id as parameter
$deleted = $person->Delete(17);
// SQL Equivalent
"DELETE FROM persons WHERE Id = 17 LIMIT 1"
```
#### Saving person's data
```php
<?php
// Update personal data
$person->Firstname = "John";
$person->Age = "20";
$person->Sex = "F";
$person->Id = "4";
// Returns affected rows
$saved = $person->Save();
// Or give the bindings to the constructor
$person = new person(array("Firstname"=>"John","age"=>"20","sex"=>"F","Id"=>"4"));
$saved = $person->Save();
// SQL Equivalent
"UPDATE persons SET Firstname = 'John',Age = 20, Sex = 'F' WHERE Id= 4"
```
#### Finding a person
```php
<?php
// Find person
$person->Id = "1";
$person->find();
echo $person->Firstname;
// Johny
// Shorthand method, give id as parameter
$person->find(1);
// SQL Equivalent
"SELECT * FROM persons WHERE Id = 1"
```
#### Getting all the persons
```php
<?php
// Finding all person
$persons = $person->all();
// SQL Equivalent
"SELECT * FROM persons
```
## Copyright and license
#### Code released under Beerware
================================================
FILE: SQL dump/testdb.sql
================================================
/*
Navicat MySQL Data Transfer
Source Server : localhost_3306
Source Server Version : 50527
Source Host : localhost:3306
Source Database : testdb
Target Server Type : MYSQL
Target Server Version : 50527
File Encoding : 65001
Date: 2012-11-12 14:07:39
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for `persons`
-- ----------------------------
DROP TABLE IF EXISTS `persons`;
CREATE TABLE `persons` (
`Id` int(11) NOT NULL AUTO_INCREMENT,
`Firstname` varchar(32) DEFAULT NULL,
`Lastname` varchar(32) DEFAULT NULL,
`Sex` char(1) DEFAULT NULL,
`Age` tinyint(3) DEFAULT NULL,
PRIMARY KEY (`Id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1;
-- ----------------------------
-- Records of persons
-- ----------------------------
INSERT INTO `persons` VALUES ('1', 'John', 'Doe', 'M', '19');
INSERT INTO `persons` VALUES ('2', 'Bob', 'Black', 'M', '40');
INSERT INTO `persons` VALUES ('3', 'Zoe', 'Chan', 'F', '21');
INSERT INTO `persons` VALUES ('4', 'Sekito', 'Khan', 'M', '19');
INSERT INTO `persons` VALUES ('5', 'Kader', 'Khan', 'M', '56');
================================================
FILE: composer.json
================================================
{
"name": "indieteq/indieteq-php-my-sql-pdo-database-class",
"description": "A database class for MySQL with PDO",
"type": "library",
"keywords": [ "mysql", "pdo", "php", "beer", "free" ],
"homepage": "https://github.com/wickyaswal/indieteq-php-my-sql-pdo-database-class",
"license": "Beerware",
"authors": [
{ "name": "wicky", "email": "info@wickyaswal.com" }
],
"require": {
"php": ">=5.3.0"
}
}
================================================
FILE: easyCRUD/Person.class.php
================================================
<?php
require_once("easyCRUD.class.php");
class Person Extends Crud {
# Your Table name
protected $table = 'persons';
# Primary Key of the Table
protected $pk = 'id';
}
?>
================================================
FILE: easyCRUD/easyCRUD.class.php
================================================
<?php
/**
* Easy Crud - This class kinda works like ORM. Just created for fun :)
*
* @author Author: Vivek Wicky Aswal. (https://twitter.com/#!/VivekWickyAswal)
* @version 0.1a
*/
require_once(__DIR__ . '/../Db.class.php');
class Crud {
private $db;
public $variables;
public function __construct($data = array()) {
$this->db = new DB();
$this->variables = $data;
}
public function __set($name,$value){
if(strtolower($name) === $this->pk) {
$this->variables[$this->pk] = $value;
}
else {
$this->variables[$name] = $value;
}
}
public function __get($name)
{
if(is_array($this->variables)) {
if(array_key_exists($name,$this->variables)) {
return $this->variables[$name];
}
}
return null;
}
public function save($id = "0") {
$this->variables[$this->pk] = (empty($this->variables[$this->pk])) ? $id : $this->variables[$this->pk];
$fieldsvals = '';
$columns = array_keys($this->variables);
foreach($columns as $column)
{
if($column !== $this->pk)
$fieldsvals .= $column . " = :". $column . ",";
}
$fieldsvals = substr_replace($fieldsvals , '', -1);
if(count($columns) > 1 ) {
$sql = "UPDATE " . $this->table . " SET " . $fieldsvals . " WHERE " . $this->pk . "= :" . $this->pk;
if($id === "0" && $this->variables[$this->pk] === "0") {
unset($this->variables[$this->pk]);
$sql = "UPDATE " . $this->table . " SET " . $fieldsvals;
}
return $this->exec($sql);
}
return null;
}
public function create() {
$bindings = $this->variables;
if(!empty($bindings)) {
$fields = array_keys($bindings);
$fieldsvals = array(implode(",",$fields),":" . implode(",:",$fields));
$sql = "INSERT INTO ".$this->table." (".$fieldsvals[0].") VALUES (".$fieldsvals[1].")";
}
else {
$sql = "INSERT INTO ".$this->table." () VALUES ()";
}
return $this->exec($sql);
}
public function delete($id = "") {
$id = (empty($this->variables[$this->pk])) ? $id : $this->variables[$this->pk];
if(!empty($id)) {
$sql = "DELETE FROM " . $this->table . " WHERE " . $this->pk . "= :" . $this->pk. " LIMIT 1" ;
}
return $this->exec($sql, array($this->pk=>$id));
}
public function find($id = "") {
$id = (empty($this->variables[$this->pk])) ? $id : $this->variables[$this->pk];
if(!empty($id)) {
$sql = "SELECT * FROM " . $this->table ." WHERE " . $this->pk . "= :" . $this->pk . " LIMIT 1";
$result = $this->db->row($sql, array($this->pk=>$id));
$this->variables = ($result != false) ? $result : null;
}
}
/**
* @param array $fields.
* @param array $sort.
* @return array of Collection.
* Example: $user = new User;
* $found_user_array = $user->search(array('sex' => 'Male', 'age' => '18'), array('dob' => 'DESC'));
* // Will produce: SELECT * FROM {$this->table_name} WHERE sex = :sex AND age = :age ORDER BY dob DESC;
* // And rest is binding those params with the Query. Which will return an array.
* // Now we can use for each on $found_user_array.
* Other functionalities ex: Support for LIKE, >, <, >=, <= ... Are not yet supported.
*/
public function search($fields = array(), $sort = array()) {
$bindings = empty($fields) ? $this->variables : $fields;
$sql = "SELECT * FROM " . $this->table;
if (!empty($bindings)) {
$fieldsvals = array();
$columns = array_keys($bindings);
foreach($columns as $column) {
$fieldsvals [] = $column . " = :". $column;
}
$sql .= " WHERE " . implode(" AND ", $fieldsvals);
}
if (!empty($sort)) {
$sortvals = array();
foreach ($sort as $key => $value) {
$sortvals[] = $key . " " . $value;
}
$sql .= " ORDER BY " . implode(", ", $sortvals);
}
return $this->exec($sql);
}
public function all(){
return $this->db->query("SELECT * FROM " . $this->table);
}
public function min($field) {
if($field)
return $this->db->single("SELECT min(" . $field . ")" . " FROM " . $this->table);
}
public function max($field) {
if($field)
return $this->db->single("SELECT max(" . $field . ")" . " FROM " . $this->table);
}
public function avg($field) {
if($field)
return $this->db->single("SELECT avg(" . $field . ")" . " FROM " . $this->table);
}
public function sum($field) {
if($field)
return $this->db->single("SELECT sum(" . $field . ")" . " FROM " . $this->table);
}
public function count($field) {
if($field)
return $this->db->single("SELECT count(" . $field . ")" . " FROM " . $this->table);
}
private function exec($sql, $array = null) {
if($array !== null) {
// Get result with the DB object
$result = $this->db->query($sql, $array);
}
else {
// Get result with the DB object
$result = $this->db->query($sql, $this->variables);
}
// Empty bindings
$this->variables = array();
return $result;
}
}
?>
================================================
FILE: easyCRUD/index.php
================================================
<?php
// Require the person class file
require("Person.class.php");
// Instantiate the person class
$person = new Person();
// Create new person
$person->Firstname = "Kona";
$person->Age = "20";
$person->Sex = "F";
$creation = $person->Create();
// Update Person Info
$person->id = "4";
$person->Age = "32";
$saved = $person->Save();
// Find person
$person->id = "4";
$person->Find();
d($person->Firstname, "Person->Firstname");
d($person->Age, "Person->Age");
// Delete person
$person->id = "17";
$delete = $person->Delete();
// Get all persons
$persons = $person->all();
// Aggregates methods
d($person->max('age'), "Max person age");
d($person->min('age'), "Min person age");
d($person->sum('age'), "Sum persons age");
d($person->avg('age'), "Average persons age");
d($person->count('id'), "Count persons");
function d($v, $t = "")
{
echo '<pre>';
echo '<h1>' . $t. '</h1>';
var_dump($v);
echo '</pre>';
}
?>
================================================
FILE: index.php
================================================
<?php
require("Db.class.php");
// Creates the instance
$db = new Db();
// 3 ways to bind parameters :
// 1. Read friendly method
$db->bind("firstname","John");
$db->bind("age","19");
// 2. Bind more parameters
$db->bindMore(array("firstname"=>"John","age"=>"19"));
// 3. Or just give the parameters to the method
$db->query("SELECT * FROM Persons WHERE firstname = :firstname AND age = :age", array("firstname"=>"John","age"=>"19"));
// Fetching data
$person = $db->query("SELECT * FROM Persons");
// If you want another fetchmode just give it as parameter
$persons_num = $db->query("SELECT * FROM Persons", null, PDO::FETCH_NUM);
// Fetching single value
$firstname = $db->single("SELECT firstname FROM Persons WHERE Id = :id ", array('id' => '3' ) );
// Single Row
$id_age = $db->row("SELECT Id, Age FROM Persons WHERE firstname = :f", array("f"=>"Zoe"));
// Single Row with numeric index
$id_age_num = $db->row("SELECT Id, Age FROM Persons WHERE firstname = :f", array("f"=>"Zoe"),PDO::FETCH_NUM);
// Column, numeric index
$ages = $db->column("SELECT age FROM Persons");
// The following statements will return the affected rows
// Update statement
$update = $db->query("UPDATE Persons SET firstname = :f WHERE Id = :id",array("f"=>"Johny","id"=>"1"));
// Insert statement
// $insert = $db->query("INSERT INTO Persons(Firstname,Age) VALUES(:f,:age)",array("f"=>"Vivek","age"=>"20"));
// Delete statement
// $delete = $db->query("DELETE FROM Persons WHERE Id = :id",array("id"=>"6"));
function d($v, $t = "")
{
echo '<pre>';
echo '<h1>' . $t. '</h1>';
var_dump($v);
echo '</pre>';
}
//d($person, "All persons");
d($id_age, "Single Row, Id and Age");
d($firstname, "Fetch Single value, The firstname");
d($ages, "Fetch Column, Numeric Index");
?>
================================================
FILE: settings.ini.php
================================================
;<?php return; ?>
[SQL]
host = localhost
user = root
password =
dbname = testdb
gitextract_d3ec_8g3/ ├── Db.class.php ├── LICENSE ├── Log.class.php ├── README.md ├── SQL dump/ │ └── testdb.sql ├── composer.json ├── easyCRUD/ │ ├── Person.class.php │ ├── easyCRUD.class.php │ └── index.php ├── index.php └── settings.ini.php
SYMBOL INDEX (40 symbols across 7 files)
FILE: Db.class.php
class DB (line 11) | class DB
method __construct (line 38) | public function __construct()
method Connect (line 53) | private function Connect()
method CloseConnection (line 82) | public function CloseConnection()
method Init (line 99) | private function Init($query, $parameters = "")
method bind (line 149) | public function bind($para, $value)
method bindMore (line 159) | public function bindMore($parray)
method query (line 177) | public function query($query, $params = null, $fetchmode = PDO::FETCH_...
method lastInsertId (line 201) | public function lastInsertId()
method beginTransaction (line 210) | public function beginTransaction()
method executeTransaction (line 219) | public function executeTransaction()
method rollBack (line 228) | public function rollBack()
method column (line 240) | public function column($query, $params = null)
method row (line 262) | public function row($query, $params = null, $fetchmode = PDO::FETCH_AS...
method single (line 276) | public function single($query, $params = null)
method ExceptionLog (line 290) | private function ExceptionLog($message, $sql = "")
FILE: Log.class.php
class Log (line 8) | class Log {
method __construct (line 14) | public function __construct() {
method write (line 32) | public function write($message) {
method edit (line 64) | private function edit($log,$date,$message) {
FILE: SQL dump/testdb.sql
type `persons` (line 22) | CREATE TABLE `persons` (
FILE: easyCRUD/Person.class.php
class Person (line 4) | class Person Extends Crud {
FILE: easyCRUD/easyCRUD.class.php
class Crud (line 9) | class Crud {
method __construct (line 15) | public function __construct($data = array()) {
method __set (line 20) | public function __set($name,$value){
method __get (line 29) | public function __get($name)
method save (line 41) | public function save($id = "0") {
method create (line 69) | public function create() {
method delete (line 84) | public function delete($id = "") {
method find (line 94) | public function find($id = "") {
method search (line 115) | public function search($fields = array(), $sort = array()) {
method all (line 139) | public function all(){
method min (line 143) | public function min($field) {
method max (line 148) | public function max($field) {
method avg (line 153) | public function avg($field) {
method sum (line 158) | public function sum($field) {
method count (line 163) | public function count($field) {
method exec (line 169) | private function exec($sql, $array = null) {
FILE: easyCRUD/index.php
function d (line 40) | function d($v, $t = "")
FILE: index.php
function d (line 48) | function d($v, $t = "")
Condensed preview — 11 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (31K chars).
[
{
"path": "Db.class.php",
"chars": 9076,
"preview": "<?php\n/**\n * DB - A simple database class \n *\n * @author\t\tAuthor: Vivek Wicky Aswal. (https://twitter.com/#!/VivekWicky"
},
{
"path": "LICENSE",
"chars": 292,
"preview": "/*\n * ----------------------------------------------------------------------------\n * \"THE BEER-WARE LICENSE\" \n * If we "
},
{
"path": "Log.class.php",
"chars": 2162,
"preview": "<?php \n /* *\n\t* Log \t\t\tA logger class which creates logs when an exception is thrown.\n\t* @author\t\tAuthor: Vivek Wi"
},
{
"path": "README.md",
"chars": 7617,
"preview": "I am not maintaining this repository anymore and I would like to request you to find a better repo or make a fork of thi"
},
{
"path": "SQL dump/testdb.sql",
"chars": 1137,
"preview": "/*\nNavicat MySQL Data Transfer\n\nSource Server : localhost_3306\nSource Server Version : 50527\nSource Host "
},
{
"path": "composer.json",
"chars": 455,
"preview": "{\n \"name\": \"indieteq/indieteq-php-my-sql-pdo-database-class\",\n \"description\": \"A database class for MySQL with PDO"
},
{
"path": "easyCRUD/Person.class.php",
"chars": 199,
"preview": "<?php \n\trequire_once(\"easyCRUD.class.php\");\n\n\tclass Person Extends Crud {\n\t\t\n\t\t\t# Your Table name \n\t\t\tprotected $table "
},
{
"path": "easyCRUD/easyCRUD.class.php",
"chars": 4836,
"preview": "<?php \n/**\n* Easy Crud - This class kinda works like ORM. Just created for fun :) \n*\n* @author\t\tAuthor: Vivek Wicky As"
},
{
"path": "easyCRUD/index.php",
"chars": 1035,
"preview": "<?php \n// Require the person class file\n require(\"Person.class.php\");\n\t\n// Instantiate the person class\n $person = "
},
{
"path": "index.php",
"chars": 1883,
"preview": "<?php\n\trequire(\"Db.class.php\");\n\n\t// Creates the instance\n\t$db = new Db();\n\t\t\n\t// 3 ways to bind parameters :\t\t\n\t\n\t// 1."
},
{
"path": "settings.ini.php",
"chars": 81,
"preview": ";<?php return; ?>\n[SQL]\nhost = localhost\nuser = root\npassword = \ndbname = testdb\n"
}
]
About this extraction
This page contains the full source code of the indieteq/indieteq-php-my-sql-pdo-database-class GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 11 files (28.1 KB), approximately 8.2k tokens, and a symbol index with 40 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.