以下是使用PDO进行数据库操作的Database类。 我为CRUD操作和启动和停止事务实现了单独的方法。
//for localhost
private static $dbName = Config::dbName;
private static $dbHost = Config::dbHost;
private static $dbUsername = Config::dbUsername;
private static $dbUserPassword = Config::dbUserPassword;
private static $cont = null;
/*
* Connect to the database
*/
public static function connect()
{
// One connection through whole application
if (null == self::$cont) {
try {
self::$cont = new PDO(
"mysql:host=" . self::$dbHost . ";"
. "dbname=" . self::$dbName, self::$dbUsername, self::$dbUserPassword);
echo '<br/>Connected to Database<br/>';
} catch (PDOException $e) {
die($e->getMessage());
}
}
return self::$cont;
}
/*
* Disconnect the database
*/
public static function disconnect()
{
echo '<br/>Disconnected to Database<br/>';
self::$cont = null;
}
/*
* Begin Trancation
*/
public function beginTransaction()
{
/* Begin a transaction, turning off autocommit */
self::connect();
echo '<br/>Begin Transaction<br/>';
self::$cont->beginTransaction();
}
/*
* Commit Trancation
*/
public function commitTransaction()
{
if (self::$cont = null) {
throw new Exception('First start transaction');
} else {
try {
echo '<br/>Commit Transaction<br/>';
/* Commit the changes */
self::$cont->commit();
/* Database connection is now back in autocommit mode */
} catch (Exception $e) {
die('Commit Error ' . $e->getMessage());
}
}
}
/**
* Prepare Query and Execute
*
* @param $query The query string
* @param $data Array of data to be insert
* @return retrun connection
*/
private function execute($query, $params)
{
// Connect to the database
$cont = $this->connect();
// Setting it to error mode
$cont->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$executor = $cont->prepare($query);
$executor->execute($params);
return $cont;
}
/**
* Insert single record to Database
*
* @param $query The query string
* @param $data Array of data to be insert
* @return last inserted id
*/
public function insert($query, $data)
{
try {
$cont = $this->execute($query, $data);
$result = $cont->lastInsertId();
echo '<br/>Data Inserted witb Id' . $result . '<br/>';
return $result;
} catch (PDOException $e) {
die($e->getMessage());
}
}
现在我试图通过以下方式使用它,它给了我致命错误
require '../class/Database.php';
echo 'Start Transaction<br/>';
$sql = "INSERT INTO pm_bib (bib_key,bib_type,bib_title,param,value) values(?, ?, ?,?,?)";
$db = new Database();
$db->beginTransaction();
echo 'Insert 1 : ok<br/>';
$param = array(1, 1, 1, 1, 1);
$db->insert($sql, $param);
echo 'Insert 2 : error<br/>';
$param = array(1, 2, 2, 2, 2);
$db->insert($sql, $param);
$db->commitTransaction();
echo 'End Transaction<br/>';