Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Basic operation of PDO

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/02 Report--

Create a PDO object

When using PDO to interact with different database management systems, the member method in the PDO object is to unify the access interface of various databases, so before using PDO to interact with the database, you should first create a PDO object. When you create an object through a constructor, you need to establish a connection to the database server and select a database

The prototype construction method of PDO is as follows

_ _ construct (string $dsn [, string $username [, string $password [, array $driver_options])

In the constructor, the first required parameter is the data source name (dsn), which is used to define a determined database and the driver that must be used. DSN's PDO naming convention is the name of the PDO driver, followed by a colon, followed by the optional driver's database connection variable information, such as hostname, port, and database name

The second parameter username and the third parameter password in the constructor specify the user name and password used to connect to the database, respectively. The last parameter, driver_options, requires an array to specify all the additional options required for the connection, passing additional tuning parameters to PDO or the underlying driver

/ * if the connection fails, use exception handling mode to catch * / $dsn = 'mysql:dbname=pdotest;host=127.0.0.1'; / / DSN $user to connect to the MySQL database =' root'; / / MySQL database user name $password ='*'; / / the password for the MySQL database try {$dbh = new PDO ($dsn, $user, $password);} catch (PDOException $e) {echo 'database connection failed:'. $e-> getMessage ();

When creating a PDO object, there are some options related to the database connection, which can be passed to the fourth parameter driver_opts of the constructor, which is used to pass additional tuning parameters to PDO or the underlying driver.

PDO::ATTR_AUTOCOMMIT): whether PDO turns off autocommit PDO::ATTR_ERRMODE): current PDO error handling mode PDO::ATTR_CASE): case conversion of table field characters: PDO::ATTR_CONNECTION_STATUS): specific information related to connection status: PDO::ATTR_ORACLE_NULLS): null PDO::ATTR_PERSISTENT for conversion of empty strings to SQL): application fetch Before getting the data big PDO::ATTR_SERVER_INFO): send a letter to the database specific server PDO::ATTR_SERVER_VERSION): database server version number information PDO::ATTR_CLIENT_VERSION): database client version number information

/ / set the array of options for persistent connections as the last parameter, you can set multiple elements $opt = array (PDO::ATTR_PERSISTENT = > true); try {$db = new PDO ('mysql:dbname=pdotest;host=127.0.0.1','root','*',$opt);} catch (PDOException $e) {echo "database connection failed:". $e-> getMessage ();}

Working with PDO objects

Adjust the behavior properties of PDO

There are many properties in the PDO object that can be used to adjust the behavior of the PDO or to get the underlying driver state. If you do not override the property option with the last parameter in the constructor when you create the PDO object, you can also set and get the values of these properties through the setAttribute () and getAttribute () methods in the PDO object after the object is created

PDO::getAttribute ()

PDO::getAttribute () is used to retrieve the properties of a database connection

Mixed PDO::getAttribute (int $attribute)

PDO::setAttribute ()

PDO::setAttribute () is used to set properties

Bool PDO::setAttribute (int $attribute, mixed $value)

$dbh- > setAttribute (PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); / / $dbh- > setAttribute (3Magne2); $dbh- > setAttribute (PDO::ATTR_AUTOCOMMIT,0); / / $dbh- > setAttribute (0Lot0); $dbh- > setAttribute (PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); / / $dbh- > setAttribute (19jue 2); echo "\ nPDO whether to turn off autocommit function:". $dbh- > getAttribute (PDO::ATTR_AUTOCOMMIT); echo "\ nThe current error handling mode of PDO:". $dbh- > getAttribute (PDO::ATTR_ERRMODE); echo "\ ncase conversion of table field characters:". $dbh- > getAttribute (PDO::ATTR_CASE); echo "\ nunique information related to connection status:". $dbh- > getAttribute (PDO::ATTR_CONNECTION_STATUS); echo "\ nempty string converted to SQL null:". $dbh- > getAttribute (PDO::ATTR_ORACLE_NULLS); echo "\ nApplication gets data size in advance:". $dbh- > getAttribute (PDO::ATTR_PERSISTENT); echo "\ n and database-specific server information:". $dbh- > getAttribute (PDO::ATTR_SERVER_INFO); echo "\ nDatabase server version number information:". $dbh- > getAttribute (PDO::ATTR_SERVER_VERSION); echo "\ nDatabase client version number information:". $dbh- > getAttribute (PDO::ATTR_CLIENT_VERSION)

Error handling

PDO provides a total of three different error handling modes, which can not only meet different styles of programming, but also adjust the way extensions handle errors.

PDO:ERRORMODE_SILENT

This is the default mode, no action is taken when the error occurs, and PDO will only set the error code. Developers can check statements and database objects through the errorCode () and errorInfo () methods in the PDO object. If the error is caused by a call to the statement object, you can call the errorCode () or errorInfo () method on that statement object. If the error is caused by calling a database object, you can call the above two methods on that database object

PDO:ERRMODE_WARNING

In addition to setting the error code, PDO emits a traditional PHP E_WARNING message, which can be captured using a regular PHP error handler. This setting is useful in debugging or testing if you just want to see what happened and have no intention of interrupting the flow of the application

$dbh- > setAttrbute (PDO::ATTR_ERRMODE,PDO::ERRMODE_WARNING); / / set warning mode to handle errors

PDO:ERRMODE_EXCEPTION

In addition to setting the error code, PDO throws a PDOException and sets its properties to reflect the error code and error message. This setting is also useful in debugging because it magnifies where errors occur in the script, allowing you to very quickly identify potential areas in your code that are problematic. Another useful aspect of exception patterns is that they can construct their own error handling more clearly than traditional PHP-style warnings, and there is less exception pattern code and nested code than silently and explicitly checking the return value of each database call.

$dbh- > setAttrbute (PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION); / / set exception mode handling error

Execute SQL statement

Before querying data using PDO, provide a set of related data. Create a PDO object and connect to the mysql database server through the mysql driver, create a database named 'testdb', and create a contact information table contactInfo in the database

CREATE TABLE contactInfo (uid MEDIUMINT (8) UNSIGNED NOT NULL AUTO_INCREMENT, name VARCHAR (50) NOT NULL, departmentID CHAR (3) NOT NULL, address VARCHAR (80) NOT NULL, phone VARCHAR (20), email VARCHAR (20), PRIMARY KEY (uid

After the data table contactInfo is established, insert multiple rows of records into the table

INSERT INTO contactInfo (name,departmentID,address,phone,email) VALUES ('Zhang San', 'D01', 'Chaoyang', '15011111234'), ('Li Si', 'D02', 'Chaoyang', '15011112345'), ('Wang Wu', 'D02', 'Haidian', '15011113456'), ('Zhao Si', 'D0114567', 'Haidian', '15011114567')

PDO::exec ()

The PDO::exec () function executes a SQL statement and returns the number of rows affected

Int PDO::exec (string $statement)

When executing queries that have no result sets, such as INSERT, UPDATE, DELETET, etc., use the exec () method in the PDO object to execute. When the method is executed successfully, the number of rows affected will be returned

PDO::lastInsertId ()

The PDO::lastInsertId () function returns the ID or sequence value of the last inserted row

String PDO::lastInsertId ([string $name = NULL])

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report