Phppdo class library usage example, phppdo Module Entry example-php Tutorial

Source: Internet
Author: User
Phppdo class library usage example, phppdo Module Entry example

  1. $ Dbh = new PDO ('MySQL: host = localhost; dbname = access_control ', 'root ','');
  2. $ Dbh-> setAttribute (PDO: ATTR_ERRMODE, PDO: ERRMODE_EXCEPTION );
  3. $ Dbh-> exec ('set names utf8 ');
  4. /* Add */
  5. // $ SQL = "INSERT INTO 'user' SET 'login' =: login AND 'password' =: password ";
  6. $ SQL = "INSERT INTO 'user' ('login', 'password') VALUES (: login,: password )"; $ stmt = $ dbh-> prepare ($ SQL); $ stmt-> execute (array (': login' => 'kevin2 ',': password '=> ''));
  7. Echo $ dbh-> lastinsertid ();
  8. /* Modify */
  9. $ SQL = "UPDATE 'user' SET 'password' =: password WHERE 'user _ id' =: userId ";
  10. $ Stmt = $ dbh-> prepare ($ SQL );
  11. $ Stmt-> execute (array (': userid' => '7',': password' => '4607e782c4d86fd5364d7e4248bb10d9 '));
  12. Echo $ stmt-> rowCount ();
  13. /* Delete */
  14. $ SQL = "DELETE FROM 'user' WHERE 'login' LIKE 'Kevin _ '"; // kevin %
  15. $ Stmt = $ dbh-> prepare ($ SQL );
  16. $ Stmt-> execute ();
  17. Echo $ stmt-> rowCount ();
  18. /* Query */
  19. $ Login = 'Kevin % ';
  20. $ SQL = "SELECT * FROM 'user' WHERE 'login' LIKE: login ";
  21. $ Stmt = $ dbh-> prepare ($ SQL );
  22. $ Stmt-> execute (array (': login' => $ login ));
  23. While ($ row = $ stmt-> fetch (PDO: FETCH_ASSOC )){
  24. Print_r ($ row );
  25. }
  26. Print_r ($ stmt-> fetchAll (PDO: FETCH_ASSOC ));
  27. ?>

1. establish a connection

  1. $ Dbh = newPDO ('MySQL: host = localhost; port = 3306; dbname = test', $ user, $ pass, array (
  2. PDO: ATTR_PERSISTENT => true
  3. ));
  4. ?>

Persistent link PDO: ATTR_PERSISTENT => true

2. capture errors

  1. Try {
  2. $ Dbh = newPDO ('MySQL: host = localhost; dbname = test', $ user, $ pass );
  3. $ Dbh-> setAttribute (PDO: ATTR_ERRMODE, PDO: ERRMODE_EXCEPTION );
  4. $ Dbh-> exec ("set character set utf8 ");
  5. $ Dbh = null; // disconnect
  6. } Catch (PDOException $ e ){
  7. Print "Error! : ". $ E-> getMessage ()."
    ";
  8. Die ();
  9. }
  10. ?>

3. Transactions

  1. Try {

  2. $ Dbh-> setAttribute (PDO: ATTR_ERRMODE, PDO: ERRMODE_EXCEPTION );
  3. $ Dbh-> beginTransaction (); // start the transaction
  4. $ Dbh-> exec ("insertintostaff (id, first, last) values (23, 'job', 'bloggs ')");
  5. $ Dbh-> exec ("insertintosalarychange (id, amount, changedate)
  6. Values (, NOW ())");
  7. $ Dbh-> commit (); // submit the transaction

  8. } Catch (Exception $ e ){

  9. $ Dbh-> rollBack (); // error rollBack
  10. Echo "Failed:". $ e-> getMessage ();
  11. }
  12. ?>

4. Error handling a. silent mode (default mode)

  1. Try {
  2. $ Dbh = new PDO ($ dsn, $ user, $ password );
  3. $ SQL = 'select * from city where CountryCode =: country ';
  4. $ Dbh-> setAttribute (PDO: ATTR_ERRMODE, PDO: ERRMODE_WARNING );
  5. $ Stmt = $ dbh-> prepare ($ SQL );
  6. $ Stmt-> bindParam (': country', $ country, PDO: PARAM_STR );
  7. $ Stmt-> execute ();
  8. While ($ row = $ stmt-> fetch (PDO: FETCH_ASSOC )){
  9. Print $ row ['name']. "/t ";
  10. }
  11. } // If there is a problem we can handle it here
  12. Catch (PDOException $ e ){
  13. Echo 'pdo Exception Caught .';
  14. Echo 'error with the database:
    ';
  15. Echo 'SQL Query:', $ SQL;
  16. Echo 'Error: '. $ e-> getMessage ();
  17. }
  18. ?>

1. use query ()

  1. $ Dbh-> query ($ SQL); when $ SQL contains variables, you can use $ dbh-> quote ($ params); // escape string data

  2. $ SQL = 'select * from city where CountryCode = '. $ dbh-> quote ($ country );

  3. Foreach ($ dbh-> query ($ SQL) as $ row ){
  4. Print $ row ['name']. "/t ";
  5. Print $ row ['countrycode']. "/t ";
  6. Print $ row ['population']. "/n ";
  7. }
  8. ?>

2. use prepare, bindParam, and execute [recommended, and can be added, modified, or deleted]

  1. $ Dbh-> prepare ($ SQL); generates a PDOStatement object.
  2. PDOStatement-> bindParam ()
  3. PDOStatement-> execute (); // you can put the bound variable here.
  4. ?>

3. Transactions

  1. Try {
  2. $ Dbh = new PDO ('MySQL: host = localhost; dbname = test', 'root ','');
  3. $ Dbh-> query ('set names utf8 ;');
  4. $ Dbh-> setAttribute (PDO: ATTR_ERRMODE, PDO: ERRMODE_EXCEPTION );
  5. $ Dbh-> beginTransaction ();
  6. $ Dbh-> exec ("Insert INTO 'test'. 'Table' ('name', 'age') VALUES ('Mick', 22 );");
  7. $ Dbh-> exec ("Insert INTO 'test'. 'Table' ('name', 'age') VALUES ('Lily', 29 );");
  8. $ Dbh-> exec ("Insert INTO 'test'. 'Table' ('name', 'age') VALUES ('Susan ', 21 );");
  9. $ Dbh-> commit ();
  10. } Catch (Exception $ e ){
  11. $ Dbh-> rollBack ();
  12. Echo "Failed:". $ e-> getMessage ();
  13. }
  14. ?>

Common PDO method: PDO: query () is mainly used for PDOStatement operations with record results, especially select operations.

PDO: exec () is mainly for operations that are not returned by the result set. Such as insert and update. Returns the number of affected rows. PDO: lastInsertId () returns the last ID of the last insert operation, but note: If you use insert into tb (col1, col2) values (v1, v2), (v11, v22 ).. lastinsertid () returns only the ID of the first (v1, v2) inserted, rather than the ID of the last inserted record. PDOStatement: fetch () is used to obtain a record. Traverse with while. PDOStatement: fetchAll () is to obtain all record sets to one. PDOStatement: fetchcolumn ([int column_indexnum]) is used to directly access a column. the parameter column_indexnum is the value of the column starting from 0 in the row. However, this method can only retrieve one column of the same row at a time. if it is executed once, it will jump to the next row. Therefore, it is easier to directly access a column, but it cannot be used to traverse multiple columns. PDOStatement: rowcount () is used to obtain the number of records when the query ("select...") method is used. It can also be used in preprocessing. $ Stmt-> rowcount (); PDOStatement: columncount () is used to obtain the number of columns of records when the query ("select...") method is used.

Note: 1. choose fetch or fetchall? When using a small record set, fetchall is highly efficient, reducing the number of retrieval times from the database. However, for a large result set, using fetchall brings a great burden to the system. The database needs to transmit too much data to the web front-end, but the efficiency is low. 2. there are several parameters for fetch () or fetchall:

Mixed pdostatement: fetch ([int fetch_style [, int cursor_orientation [, int cursor_offset]) array pdostatement: fetchAll (int fetch_style)

Fetch_style parameters:

$ Row = $ rs-> fetchAll (PDO: FETCH_BOTH); FETCH_BOTH is the default value, which can be saved and returns associations and indexes. $ Row = $ rs-> fetchAll (PDO: FETCH_ASSOC); the FETCH_ASSOC parameter determines that only the associated array is returned. $ Row = $ rs-> fetchAll (PDO: FETCH_NUM); returns the index array $ row = $ rs-> fetchAll (PDO: FETCH_OBJ); if fetch () returns the object. for fetchall (), returns a two-dimensional array composed of objects.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.