Mình cũng chạy lăng nhăng, mỗi thứ một tí, được giao cái gì thì làm cái đó. Hôm nay vớ phải cái project , mở ra , rối bời, lại đi tìm hiểu PDO. Vớ được tài liệu ,vừa học vừa thực hành post luôn.
Các bạn có thể tham khảo thêm :http://www.php.net/manual/en/pdo.installation.php
PDO là gì : PHP Data Object
Nghĩ xem, mình vẫn thường mysql_connect hay mysql_fetch...Nhưng có một tool hay là (thô lỗ) là dùng qua PDO, trước khi vào db lấy cái gì ra , theo quen thuộc là cứ xộc vào lấy ra, điều này không tốt cho lăm. PDO giải quyết vấn đề đó, trong Java, theo mình biết cũng đã xử lý cái này từ khá lâu(nhảy cóc) . PDO có một lợi thế nữa là cho chúng ta một cách thức đa kết nối ( multi access to multiple database ):
- DBLIB: FreeTDS / Microsoft SQL Server / Sybase
- Firebird (http://firebird.sourceforge.net/): Firebird/Interbase 6
- IBM (IBM DB2)
- INFORMIX - IBM Informix Dynamic Server
- MYSQL (http://www.mysql.com/): MySQL 3.x/4.0
- OCI (http://www.oracle.com): Oracle Call Interface
- ODBC: ODBC v3 (IBM DB2 and unixODBC)
- PGSQL (http://www.postgresql.org/): PostgreSQL
- SQLITE (http://sqlite.org/): SQLite 3.x
Một ví dụ xem các driver của PDO như sau:
<?phpforeach(PDO::getAvailableDrivers() as $driver)
{
echo $driver.'<br />';
}?>
Install PDO in Ubuntu Mình đang dùng ubuntu nên mình sẽ hướng dẫn cài luôn, còn trên window, google sẽ giúp sau vậy .
Bật terminal lên :
sudo apt-get install php5-dev
sudo apt-get install php-pear
sudo apt-get install libmysqlclient15-dev
sudo pecl install pdo
PHP_PDO_SHARED=1 sudo pecl install pdo_mysql
Sau đó vào php.ini (/etc/php5/apache2/) paste cái này vào cuối :
extension=pdo.so
extension=pdo_mysql.so
Hoặc vào đây : http://svn.php.net/viewvc/php/php-src/trunk/ext/
Sau đây là một số các kết nối phổ biến :
Mình định viết câu này ở cuối nhưng lại đặt lên đầu, để không tiếc:
Hãy viết lại từng dòng một hand by hand, replace table,id bằng những dbid của mình, xem kết quả.
PDO sẽ rất tốt cho ai muốn tìm hiểu để xây dựng một DBOject cho riêng mình.
Connect with PgSQL
<?phptry {
$db = new PDO("pgsql:dbname=pdo;host=localhost", "username", "password" );
echo "PDO connection object created";
}
catch(PDOException $e)
{
echo $e->getMessage();
}?>
Connect to SQLite
<?php
try {
/*** connect to SQLite database ***/
$dbh = new PDO("sqlite:/path/to/database.sdb");
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
Connect to MySQL
<?php
/*** mysql hostname ***/
$hostname = 'localhost';
/*** mysql username ***/
$username = 'username';
/*** mysql password ***/
$password = 'password';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=mysql", $username, $password);
/*** echo a message saying we have connected ***/
echo 'Connected to database';
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
Connect to Firebird
<?php
try {
$dbh = new PDO("firebird:dbname=localhost:C:\Programs\Firebird\DATABASE.FDB", "SYSDBA", "masterkey");
}
catch (PDOException $e)
{
echo $e->getMessage();
}
?>
Connect to Informix
<?php
try {
$dbh = new PDO("informix:DSN=InformixDB", "username", "password");
}
catch (PDOException $e)
{
echo $e->getMessage();
}
?>
Connect to Oracle
<?php
try {
$dbh = new PDO("OCI:", "username", "password")
}
catch (PDOException $e)
{
echo $e->getMessage();
}
?>
Connect to ODBC
<?php
try {
$dbh = new PDO("odbc:Driver={Microsoft Access Driver (*.mdb)};Dbq=C:\accounts.mdb;Uid=Admin");
}
catch (PDOException $e)
{
echo $e->getMessage();
}
?>
Connect to DBLIB
<?php
try {
$hostname = "localhost";
$port = 10060;
$dbname = "my_database";
$username = "username";
$password = "password";
$dbh = new PDO ("dblib:host=$hostname:$port;dbname=$dbname","$username","$password");
}
catch (PDOException $e)
{
echo $e->getMessage();
}
?>
Connect to IBM
<?php
try {
$db = new PDO("ibm:DRIVER={IBM DB2 ODBC DRIVER};DATABASE=accounts; HOSTNAME=1.2.3,4;PORT=56789;PROTOCOL=TCPIP;", "username", "password");
}
catch (PDOException $e)
{
echo $e->getMessage();
}
?>
Close a Database Connection
Sau khi kết nối, thử xem query có khác nhiều hay khó hơn với query basic không .
<?php/*** mysql hostname ***/$hostname = 'localhost';/*** mysql username ***/$username = 'username';/*** mysql password ***/$password = 'password';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=mysql", $username, $password);
/*** echo a message saying we have connected ***/
echo 'Connected to database';
/*** close the database connection ***/
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
PDO Query
INSERT
<?php/*** mysql hostname ***/$hostname = 'localhost';/*** mysql username ***/$username = 'username';/*** mysql password ***/$password = 'password';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$
dbname
", $username, $password);
/*** echo a message saying we have connected ***/
echo 'Connected to database<br />';
/*** INSERT data ***/
$count = $dbh->exec("INSERT INTO tablename(id1,id2) VALUES ('val1', 'val2')");
/*** echo the number of affected rows ***/
echo $count;
/*** close the database connection ***/
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}?>
SELECT
<?php/*** mysql hostname ***/$hostname = 'localhost';/*** mysql username ***/$username = 'username';/*** mysql password ***/$password = 'password';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=
$dbname
", $username, $password);
/*** echo a message saying we have connected ***/
echo 'Connected to database<br />';
/*** The SQL SELECT statement ***/
$sql = "SELECT * FROM table";
foreach ($dbh->query($sql) as $row)
{
print $row['val1'] .' - '. $row['val1'] . '<br />';
}
/*** close the database connection ***/
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}?>
UPDATE
<?php/*** mysql hostname ***/$hostname = 'localhost';/*** mysql username ***/$username = 'username';/*** mysql password ***/$password = 'password';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=
$dbname
", $username, $password);
/*** echo a message saying we have connected ***/
echo 'Connected to database<br />';
/*** INSERT data ***/
$count = $dbh->exec("UPDATE table SET id1='val1' WHERE id1='val1'");
/*** echo the number of affected rows ***/
echo $count;
/*** close the database connection ***/
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}?>
FETCH Modes
FETCH ASSOC
<?php/*** mysql hostname ***/$hostname = 'localhost';/*** mysql username ***/$username = 'username';/*** mysql password ***/$password = 'password';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=
$dbname
", $username, $password);
/*** echo a message saying we have connected ***/
echo 'Connected to database<br />';
/*** The SQL SELECT statement ***/
$sql = "SELECT * FROM table";
/*** fetch into an PDOStatement object ***/
$stmt = $dbh->query($sql);
/*** echo number of columns ***/
$result = $stmt->fetch(PDO::ableFETCH_ASSOC);
/*** loop over the object directly ***/
foreach($result as $key=>$val)
{
echo $key.' - '.$val.'<br />';
}
/*** close the database connection ***/
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}?>
FETCH NUM
<?php/*** mysql hostname ***/$hostname = 'localhost';/*** mysql username ***/$username = 'username';/*** mysql password ***/$password = 'password';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=animals", $username, $password);
/*** echo a message saying we have connected ***/
echo 'Connected to database<br />';
/*** The SQL SELECT statement ***/
$sql = "SELECT * FROM animals";
/*** fetch into an PDOStatement object ***/
$stmt = $dbh->query($sql);
/*** echo number of columns ***/
$result = $stmt->fetch(PDO::FETCH_NUM);
/*** loop over the object directly ***/
foreach($result as $key=>$val)
{
echo $key.' - '.$val.'<br />';
}
/*** close the database connection ***/
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}?>
FETCH BOTH
<?php/*** mysql hostname ***/$hostname = 'localhost';/*** mysql username ***/$username = 'username';/*** mysql password ***/$password = 'password';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$
dbname
", $username, $password);
/*** echo a message saying we have connected ***/
echo 'Connected to database<br />';
/*** The SQL SELECT statement ***/
$sql = "SELECT * FROM table";
/*** fetch into an PDOStatement object ***/
$stmt = $dbh->query($sql);
/*** echo number of columns ***/
$result = $stmt->fetch(PDO::FETCH_BOTH);
/*** loop over the object directly ***/
foreach($result as $key=>$val)
{
echo $key.' - '.$val.'<br />';
}
/*** close the database connection ***/
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}?>
FETCH OBJECT
<?php/*** mysql hostname ***/$hostname = 'localhost';/*** mysql username ***/$username = 'username';/*** mysql password ***/$password = 'password';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$
dbname
", $username, $password);
/*** echo a message saying we have connected ***/
echo 'Connected to database<br />';
/*** The SQL SELECT statement ***/
$sql = "SELECT * FROM table";
/*** fetch into an PDOStatement object ***/
$stmt = $dbh->query($sql);
/*** echo number of columns ***/
$obj = $stmt->fetch(PDO::FETCH_OBJ);
/*** loop over the object directly ***/
echo $obj->id1.'<br />';
echo $obj->id2.'<br />';
echo $obj->id3;
/*** close the database connection ***/
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}?>
FETCH LAZY
<?php/*** mysql hostname ***/$hostname = 'localhost';/*** mysql username ***/$username = 'username';/*** mysql password ***/$password = 'password';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$
dbname
", $username, $password);
/*** echo a message saying we have connected ***/
echo 'Connected to database<br />';
/*** The SQL SELECT statement ***/
$sql = "SELECT * FROM animals";
/*** fetch into an PDOStatement object ***/
$stmt = $dbh->query($sql);
/*** echo number of columns ***/
$result = $stmt->fetch(PDO::FETCH_BOTH);
/*** loop over the object directly ***/
foreach($result as $key=>$val)
{
echo $key.' - '.$val.'<br />';
}
/*** close the database connection ***/
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}?>
FETCH CLASS
<?phpclass table{
public $id1;
public $id2;
public $id3;/***
*
* @capitalize first words
*
* @access public
*
* @return string
*
*/public function capitalizeType(){
return ucwords($this->id1);
}
} /*** end of class ***/
/*** mysql hostname ***/$hostname = 'localhost';/*** mysql username ***/$username = 'username';/*** mysql password ***/$password = 'password';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=
$dbname
", $username, $password);
/*** echo a message saying we have connected ***/
echo 'Connected to database<br />';
/*** The SQL SELECT statement ***/
$sql = "SELECT * FROM table";
/*** fetch into an PDOStatement object ***/
$stmt = $dbh->query($sql);
/*** fetch into the animals class ***/
$obj = $stmt->fetchALL(PDO::FETCH_CLASS, 'table');
/*** loop of the object directly ***/
foreach($obj as $animals)
{
/*** call the capitalizeType method ***/
echo $animals->capitalizeType().'<br />';
}
/*** close the database connection ***/
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}?>
<?phpclass table{
public $id1;
public $id2;
public $id3;/***
*
* @capitalize first words
*
* @access public
*
* @return string
*
*/public function capitalizeType(){
return ucwords($this->id1);
}
} /*** end of class ***/
/*** mysql hostname ***/$hostname = 'localhost';/*** mysql username ***/$username = 'username';/*** mysql password ***/$password = 'password';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$
dbname
", $username, $password);
/*** echo a message saying we have connected ***/
echo 'Connected to database<br />';
/*** The SQL SELECT statement ***/
$sql = "SELECT * FROM table";
/*** fetch into an PDOStatement object ***/
$stmt = $dbh->query($sql);
/*** fetch into the animals class ***/
$animals = $stmt->fetchObject('table');
/*** echo the class properties ***/
echo $animals->id1.'<br />';
echo $animals->capitalizeType().'<br />';
echo $animals->id2;
/*** close the database connection ***/
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}?>
FETCH INTO
<?phpclass table{
public $id1;
public $
id
2;
public $
id3
;
public function capitalizeType(){
return ucwords($this->get_type);
}
} /*** end of class ***/
/*** instantiate a new animals instance ***/$ob = new table;$ob->id1= 10;
$ob
->id2 = 'id2';
$ob
->id3 = 'id3';/*** mysql hostname ***/$hostname = 'localhost';/*** mysql username ***/$username = 'username';/*** mysql password ***/$password = 'password';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
/*** echo a message saying we have connected ***/
echo 'Connected to database<br />';
/*** The SQL SELECT statement ***/
$sql = "SELECT * FROM table";
/*** fetch into an PDOStatement object ***/
$stmt = $dbh->query($sql);
/*** set the fetch mode with PDO::setFetchMode() ***/
$stmt->setFetchMode(PDO::FETCH_INTO, new table);
/*** loop over the PDOStatement directly ***/
foreach($stmt as $obdata)
{
echo $obdata->capitalizeType().'<br />';
}
/*** close the database connection ***/
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}?>
Error Handling
<?php/*** mysql hostname ***/$hostname = 'localhost';/*** mysql username ***/$username = 'username';/*** mysql password ***/$password = 'password';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=
$dbname
", $username, $password);
/*** echo a message saying we have connected ***/
echo 'Connected to database<br />';
/*** The SQL SELECT statement with incorrect fieldname ***/
$sql = "SELECT id1 FROM table";
foreach ($dbh->query($sql) as $row)
{
print $row['id1'] .' - '. $row['id2'] . '<br />';
}
/*** close the database connection ***/
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}?>
<?php/*** mysql hostname ***/$hostname = 'localhost';/*** mysql username ***/$username = 'username';/*** mysql password ***/$password = 'password';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$
dbname
", $username, $password);
/*** echo a message saying we have connected ***/
echo 'Connected to database<br />';
/*** set the error reporting attribute ***/
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
/*** The SQL SELECT statement ***/
$sql = "SELECT id1 FROM table";
foreach ($dbh->query($sql) as $row)
{
print $row['id1'] .' - '. $row['id2'] . '<br />';
}
/*** close the database connection ***/
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}?>
<?php/*** mysql hostname ***/$hostname = 'localhost';/*** mysql username ***/$username = 'username';/*** mysql password ***/$password = 'password';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$
dbname
", $username, $password);
/*** echo a message saying we have connected ***/
echo 'Connected to database<br />';
/*** set the error reporting attribute ***/
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
/*** The SQL SELECT statement ***/
$sql = "SELECT id1 FROM table";
foreach ($dbh->query($sql) as $row)
{
print $row['
id1
'] .' - '. $row['
id2
'] . '<br />';
}
/*** close the database connection ***/
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}?>
<?php/*** mysql hostname ***/$hostname = 'localhost';/*** mysql username ***/$username = 'username';/*** mysql password ***/$password = 'password';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=
$dbname
", $username, $password);
/*** echo a message saying we have connected ***/
echo 'Connected to database<br />';
/*** set the error reporting attribute ***/
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
/*** The SQL SELECT statement ***/
$sql = "SELECT id1 FROM table";
foreach ($dbh->query($sql) as $row)
{
print $row['
id1
'] .' - '. $row['
id2
'] . '<br />';
}
/*** close the database connection ***/
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}?>
<?php/*** mysql hostname ***/$hostname = 'localhost';/*** mysql username ***/$username = 'username';/*** mysql password ***/$password = 'password';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=
$dbname
", $username, $password);
/*** echo a message saying we have connected ***/
echo 'Connected to database<br />';
}
catch(PDOException $e)
{
echo $e->getMessage();
}/*** an invalide fieldname ***/$sql = "SELECT id1 FROM table";/*** run the query ***/$result = $dbh->query($sql);/*** show the error code ***/echo $dbh->errorCode();?>
<?php/*** mysql hostname ***/$hostname = 'localhost';/*** mysql username ***/$username = 'username';/*** mysql password ***/$password = 'password';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
/*** echo a message saying we have connected ***/
echo 'Connected to database<br />';
}
catch(PDOException $e)
{
echo $e->getMessage();
}/*** an invalid table name ***/$sql = "SELECT id1 FROM tablerror;/*** run the query ***/$result = $dbh->query($sql);/*** show the error info ***/foreach($dbh->errorInfo() as $error)
{
echo $error.'<br />';
}?>
Prepared statements
<?php/*** mysql hostname ***/$hostname = 'localhost';/*** mysql username ***/$username = 'username';/*** mysql password ***/$password = 'password';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=
$dbname
", $username, $password);
/*** echo a message saying we have connected ***/
echo 'Connected to database<br />';
/*** set the error reporting attribute ***/
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
/*** some variables ***/
$id1 = 1;
$id2 = 'id2';
/*** prepare the SQL statement ***/
$stmt = $dbh->prepare("SELECT * FROM talbe WHERE id1 = :id AND id2= :id2");
/*** bind the paramaters ***/
$stmt->bindParam(':id1', $id1 PDO::PARAM_INT);
$stmt->bindParam(':id2', $id2, PDO::PARAM_STR, 5);
/*** execute the prepared statement ***/
$stmt->execute();
/*** fetch the results ***/
$result = $stmt->fetchAll();
/*** loop of the results ***/
foreach($result as $row)
{
echo $row['id1'].'<br />';
echo $row['id2'].'<br />';
echo $row['id3'];
}
/*** close the database connection ***/
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}?>
<?php/*** mysql hostname ***/$hostname = 'localhost';/*** mysql username ***/$username = 'username';/*** mysql password ***/$password = 'password';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$
dbname
", $username, $password);
/*** echo a message saying we have connected ***/
echo 'Connected to database<br />';
/*** set the error reporting attribute ***/
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
/*** some variables ***/
$id1 = 1;
$id2 = 'id2';
/*** prepare the SQL statement ***/
$stmt = $dbh->prepare("SELECT * FROM table WHERE id1 = :id1 AND id2 = :id2");
/*** bind the paramaters ***/
$stmt->bindParam(':id1', $id2, PDO::PARAM_INT);
$stmt->bindParam(':id2', $id2, PDO::PARAM_STR, 5);
/*** reassign the animal_id ***/
$id1 = 3;
/*** execute tid1e prepared statement ***/
$stmt->execute();
/*** loop over the results ***/
while($row = $stmt->fetch())
{
echo $row['id1'].'<br />';
echo $row['id2'].'<br />';
echo $row['id3'];
}
/*** close the database connection ***/
$dbh = null;
}id3
catch(PDOException $e)
{
echo $e->getMessage();
}?>
Transactions
<?php/*** mysql hostname ***/$hostname = 'localhost';/*** mysql username ***/$username = 'username';/*** mysql password ***/$password = 'password';/*** database name ***/$dbname = 'animals';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
/*** echo a message saying we have connected ***/
echo 'Connected to database<br />';
/*** set the PDO error mode to exception ***/
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
/*** begin the transaction ***/
$dbh->beginTransaction();
/*** CREATE table statements ***/
$table = "CREATE TABLE id1 ( id1 MEDIUMINT(8) NOT NULL AUTO_INCREMENT PRIMARY KEY,
id1
VARCHAR(25) NOT NULL,
id2
VARCHAR(25) NOT NULL
)";
$dbh->exec($table);
/*** INSERT statements ***/
$dbh->exec("INSERT INTO table (id1,
id2
) VALUES ('1', 'id2')");
$dbh->exec("INSERT INTO
table
(id1,
id2
)
VALUES ('2', '
id3
')");
$dbh->exec("INSERT INTO
table
(id1,
id2
)
VALUES ('3', '
id4
')");
$dbh->exec("INSERT INTO
table
(id1,
id2
)
VALUES ('4', '
id5
')");
$dbh->exec("INSERT INTO
table
(id1,
id2
)
VALUES ('5', '
id6
')");
$dbh->exec("INSERT INTO
table
(id1,
id2
)
VALUES ('6', '
id7
')");
$dbh->exec("INSERT INTO
table
(id1,
id2
)
VALUES ('7', '
id8
')");
$dbh->exec("INSERT INTO
table
(id1,
id2
)
VALUES ('8', '
id9
')");
$dbh->exec("INSERT INTO
table
(id1,
id2
)
VALUES ('9', '
id10
')");
/*** commit the transaction ***/
$dbh->commit();
/*** echo a message to say the database was created ***/
echo 'Data entered successfully<br />';
}
catch(PDOException $e)
{
/*** roll back the transaction if we fail ***/
$dbh->rollback();
/*** echo the sql statement and error message ***/
echo $sql . '<br />' . $e->getMessage();
}?>
Get Last Insert Id
<?php/*** mysql hostname ***/$hostname = 'localhost';/*** mysql username ***/$username = 'username';/*** mysql password ***/$password = 'password';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=
$dbname
", $username, $password);
/*** echo a message saying we have connected ***/
echo 'Connected to database<br />';
/*** set the error reporting attribute ***/
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
/*** INSERT a new row ***/
$dbh->exec("INSERT INTO table(id1, id2) VALUES ('1', 'id2')");
/*** display the id of the last INSERT ***/
echo $dbh->lastInsertId();
/*** close the database connection ***/
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}?>
A Global Instance
<?phpclass db{/*** Declare instance ***/private static $instance = NULL;/**
*
* the constructor is set to private so
* so nobody can create a new instance using new
*
*/private function __construct() {
/*** maybe set the db name here later ***/}/**
*
* Return DB instance or create intitial connection
*
* @return object (PDO)
*
* @access public
*
*/public static function getInstance() {
if (!self::$instance)
{
self::$instance = new PDO("mysql:host='localhost';dbname='animals'", 'username', 'password');;
self::$instance-> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
return self::$instance;
}/**
*
* Like the constructor, we make __clone private
* so nobody can clone the instance
*
*/private function __clone(){
}
} /*** end of class ***/try {
/*** query the database ***/
$result = DB::getInstance()->query("SELECT * FROM animals");
/*** loop over the results ***/
foreach($result as $row)
{
print $row['animal_type'] .' - '. $row['animal_name'] . '<br />';
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}?>
End . . . stop talking nonsense! , come back to work
No comments:
Post a Comment