|
|
楼主 |
发表于 2011-8-4 15:09:50
|
显示全部楼层
Test the MySQL Database Connectivity Using the PDO Extension
 |
The following sample PHP script shows how to connect to a MySQL database running on the same host, using the PDO interface. The code sample connects to the MySQL database test by using the PDO API, sends out a query to retrieve all the rows from the table City, extracts the data from the result set, displays the data on the standard output, inserts a couple of new records into the City table using prepared statements, and finally commits the INSERT transactions. To minimize the dependencies, this script is shown as a stand-alone script rather than a PHP page that can be accessed over the web server.
The sample code is provided for the purpose of demonstration only; it is not meant to indicate that readers should adopt a particular style of coding. To keep it simple, the sample code assumes that the user always provides well-formed input, hence there is no explicit error checking code in the following example. Use discretion in reusing the sample code.
- bash# cat PHPpdoClient.php
- <?php
- $dsn='mysql:host=localhost;port=3306;dbname=test';
- $user='root';
- $pass='admin';
- try {
- /* obtain a database connection handle */
- $dbh = new PDO($dsn, $user, $pass);
- } catch (PDOException $exception) {
- printf("Failed to connect to the database. Error: %s", $exception->getMessage());
- }
- $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
- $dbh->setAttribute(PDO::ATTR_AUTOCOMMIT, false);
- $sql = "SELECT * FROM City";
- /* execute the query */
- $rs = $dbh->query($sql);
- print "\nRetrieved " . $rs->rowCount() . " row(s).\n";
- print "\nCityName\n--------\n";
- /* retrieve the data from the result set */
- $rs->setFetchMode(PDO::FETCH_ASSOC);
- while ($row = $rs->fetch()) {
- $data = $row["CityName"];
- print "$data\n";
- }
- /* close the result set */
- $rs->closeCursor();
- try {
- /* create a prepared statement */
- $query = "INSERT INTO City VALUES (?)";
- $stmt = $dbh->prepare($query);
- $city = 'London, UK';
- /* bind the parameter */
- $stmt->bindParam(1, $city);
- $dbh->beginTransaction();
- /* execute the SQL */
- if ($stmt->execute()) {
- $dbh->commit();
- echo "\nSuccessfuly inserted " . $city . " into the table, City.";
- } else {
- print_r($dbh->errorInfo());
- }
- $city = 'Paris, France';
- /* bind the parameter with another value */
- $stmt->bindParam(1, $city);
- $dbh->beginTransaction();
- /* execute the SQL again */
- if ($stmt->execute()) {
- $dbh->commit();
- echo "\nSuccessfuly inserted " . $city . " into the table, City.\n";
- } else {
- print_r($dbh->errorInfo());
- }
- $sql = "SELECT * FROM City";
- /* execute the query */
- $rs = $dbh->query($sql);
- print "\nRetrieved " . $rs->rowCount() . " row(s).\n";
- print "\nCityName\n--------\n";
- /* retrieve the data from the result set */
- $rs->setFetchMode(PDO::FETCH_OBJ);
- while ($row = $rs->fetch()) {
- $data = $row->CityName;
- print "$data\n";
- }
- /* close the result set */
- $rs->closeCursor();
- } catch (PDOException $exception) {
- print "\nException: " . $exception->getMessage();
- $dbh->rollBack();
- }
- /* close the database connection */
- $dbh = null;
- ?>
- bash# php PHPpdoClient.php
- Retrieved 3 row(s).
- CityName
- --------
- Hyderabad, India
- San Francisco, USA
- Sydney, Australia
- Successfuly inserted London, UK into the table, City.
- Successfuly inserted Paris, France into the table, City.
- Retrieved 5 row(s).
- CityName
- --------
- Hyderabad, India
- San Francisco, USA
- Sydney, Australia
- London, UK
- Paris, France
复制代码
Some of the important steps in the above code sample are explained below.
Make a Connection to the Database
Before interacting with a database using PDO, the first thing to do is to create a PDO object to use as the database handle. This is accomplished by calling PDO's constructor.
| PDO::__construct (string $dsn [, string $username [, string $password [, array $driver_options]]]) |
where: $dsn is the Data Source Name, which is composed of the following elements: the name of the PDO database driver followed by a colon, followed by optional driver-specific information. In the case of the PDO_MYSQL driver, the DSN prefix is "mysql:", and the PDO mysql driver accepts host, port, dbname and unix_socket as the optional parameters. Note that host or port and unix_socket are mutually exclusive, and hence should not be mixed in the same DSN.
The following statement in the sample PHP script attempts to connect to a MySQL server running on the localhost on the default port 3306 with the credentials root/admin, and selects the test database to perform the subsequent transactions against.
| $dbh = new PDO('mysql:host=localhost;port=3306;dbname=test', 'root', 'admin'); |
The above statement can be rewritten as shown below with the assumption that /tmp/dbconnect exists with appropriate file permissions that enable PHP to read the file.
- $dbh = new PDO('uri:file:///tmp/dbconnect', 'root', 'admin');
- bash# cat /tmp/dbconnect
- mysql:host=localhost;port=3306;dbname=test;
复制代码
If the host is localhost, then the port number is ignored and 3306 is assumed by default. If the MySQL server is running on any port other than the default port 3306, use the IP address 127.0.0.1 in place of localhost in the host argument.
If you wish to use persistent connections, you must set the attribute PDO::ATTR_PERSISTENT in the array of driver options passed to the PDO constructor. The database driver does not use persistent connections if this attribute has been set with PDO::setAttribute() after instantiating the object.
For example:
| $dbh = new PDO('mysql:host=localhost;port=3306;dbname=test', 'root', 'admin', array(PDO::ATTR_PERSISTENT => true)); |
PDO::__construct() throws a PDOException if the attempt to connect to the requested database fails.
|
|