Skip to content

Instantly share code, notes, and snippets.

@tak1827
Created June 22, 2015 11:32
Show Gist options
  • Save tak1827/ddc4076ec11a2c5db611 to your computer and use it in GitHub Desktop.
Save tak1827/ddc4076ec11a2c5db611 to your computer and use it in GitHub Desktop.
<?php
/**
* File: PdoApi.php
*
* Using this you can write PDO related code only one line.
* Example
* (new PdoApi('db', 'name', 'pass', 'host'))->exec('select * from table');
*
* @author takayuki.tamura
* @version 1.0.0
*/
class PdoApi
{
public $dbh;
function __construct($dbName, $dbUser, $pass, $host) {
$dsn = 'mysql:dbname='.$dbName.';host='.$host;
try {
$this->dbh = new PDO($dsn, $dbUser, $pass);
$this->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e){
print('Error:'.$e->getMessage());
die();
}
}
public function exec($sql) {
try {
$this->dbh->beginTransaction();
$sth = $this->dbh->query($sql);
$this->dbh->commit();
return $sth;
} catch (PDOException $e){
$this->dbh->rollBack();
print('Error:'.$e->getMessage());
die();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment