PHP MySQL PDO use

Source: Internet
Author: User
Tags error handling getmessage php mysql prepare rowcount stmt vars

[PHP]View Plaincopyprint?
  1. <?php
  2. $DBH = New PDO (' Mysql:host=localhost;dbname=access_control ', ' root ', ' );
  3. $DBH->setattribute (Pdo::attr_errmode, pdo::errmode_exception);
  4. $DBH, EXEC (' Set names UTF8 ');
  5. /* Add */
  6. $sql = "INSERT into ' user ' SET ' login ' =:login and ' password ' =:p assword";
  7. $sql = "INSERT into ' user ' (' login ', ' password ') VALUES (: Login,:p assword)";  $stmt = $dbh->prepare ($sql);    $stmt->execute (': Login ' = 'kevin2 ',':p assword ' = ') ');
  8. echo $dbh->lastinsertid ();
  9. /* Modify */
  10. $sql = "UPDATE ' user ' SET ' password ' =:p assword WHERE ' user_id ' =:userid";
  11. $stmt = $dbh->prepare ($sql);
  12. $stmt->execute (Array (': userId ' = '7 ', ':p assword ' =')    4607e782c4d86fd5364d7e4508bb10d9 '));
  13. echo $stmt->rowcount ();
  14. /* Delete */
  15. $sql = "DELETE from ' user ' WHERE ' login ' like ' kevin_ '"; //kevin%
  16. $stmt = $dbh->prepare ($sql);
  17. $stmt->execute ();
  18. echo $stmt->rowcount ();
  19. /* Query */
  20. $login = ' kevin% ';
  21. $sql = "select * from ' user ' WHERE ' login ' Like:login";
  22. $stmt = $dbh->prepare ($sql);
  23. $stmt->execute (Array (': Login ' =$login));
  24. while ($row = $stmt->fetch (PDO::FETCH_ASSOC)) {
  25. Print_r ($row);
  26. }
  27. Print_r ( $stmt->fetchall (PDO::FETCH_ASSOC));
  28. ?>


1 Establishing the connection

[PHP]View Plaincopyprint?
    1. <?php
    2. $DBH =newpdo (' mysql:host=localhost;port=3306; Dbname=test ',$user,$pass,Array (
    3. Pdo::attr_persistent=>true
    4. ));
    5. ?>


Persistent link Pdo::attr_persistent=>true

2. Catching errors

[PHP]View Plaincopyprint?
  1. <?php
  2. try{
  3. $DBH =newpdo (' mysql:host=localhost;dbname=test ',$user,$pass);
  4. $DBH->setattribute (pdo::attr_errmode,pdo::errmode_exception);
  5. exec, $DBH ("set CHARACTER set UTF8");
  6. $DBH =null; //Disconnect
  7. }catch (pdoexception$e) {
  8. Print"error!:". $e->getmessage ().  "<br/>";
  9. Die ();
  10. }
  11. ?>


3. The Business

[PHP]View Plaincopyprint?
  1. <?php
  2. try{
  3. $DBH->setattribute (pdo::attr_errmode,pdo::errmode_exception);
  4. $DBH->begintransaction (); //Open transaction
  5. exec (Insertintostaff (id,first,last) VALUES (at $, ' Joe ', ' Bloggs '), $DBH.
  6. exec, $DBH ("Insertintosalarychange (id,amount,changedate)
  7. VALUES (23,50000,now ()) ");
  8. $DBH->commit (); //Commit a transaction
  9. }catch (Exception$e) {
  10. $DBH->rollback (); //Error rollback
  11. Echo"Failed:".   $e->getmessage ();
  12. }
  13. ?>


4. Error handling

A. Silent mode (default mode)

$DBH->setattribute (pdo::attr_errmode,pdo::errmode_silent); Do not display errors

$DBH->setattribute (Pdo::attr_errmode, pdo::errmode_warning);//Display warning error, and continue execution

$DBH->setattribute (pdo::attr_errmode,pdo::errmode_exception);//Generate fatal error, pdoexception

[PHP]View Plaincopyprint?
  1. <?php
  2. try{
  3. $DBH = new PDO ($dsn, $user, $password);
  4. $sql = ' Select * from city where CountryCode =:country ';
  5. $dbh->setattribute (Pdo::attr_errmode, pdo::errmode_warning);
  6. $stmt = $dbh->prepare ($sql);
  7. $stmt->bindparam (': Country ', $country, PDO::P aram_str);
  8. $stmt->execute ();
  9. While ($row = $stmt->fetch (PDO::FETCH_ASSOC)) {
  10. Print $row [' Name '].      "/t";
  11. }
  12. } //If there is a problem we can handle it here
  13. catch (pdoexception $e) {
  14. echo ' PDO Exception caught.      ‘;
  15. echo ' Error with the database: <br/> ';
  16. echo ' SQL Query: ', $sql;
  17. echo ' Error: '.    $e->getmessage ();
  18. }
  19. ?>


1. Use Query ()

[PHP]View Plaincopyprint?
  1. <?php
  2. $DBH->query ($sql), when the variables in the $sql can be $dbh->quote ($params); //Escape string data
  3. $sql = ' Select * from city where CountryCode = '.     $DBH->quote ($country);
  4. foreach ($dbh->query ($sql) as $row) {
  5. Print $row [' Name '].      "/t";
  6. Print $row [' CountryCode '].      "/t";
  7. Print $row [' Population '].   "/n";
  8. }
  9. ?>


2. Use prepare, Bindparam and execute [recommended, and can be added, modified, deleted]

[PHP]View Plaincopyprint?
    1. <?php
    2. $DBH->prepare ($sql); A Pdostatement object was created
    3. Pdostatement->bindparam ()
    4. Pdostatement->execute (); //You can put the corresponding variable in the binding here
    5. ?>


3. Things

[PHP]View Plaincopyprint?
  1. <?php
  2. try {
  3. $DBH = new PDO (' mysql:host=localhost;dbname=test ', ' root ', ' );
  4. $dbh->query (' Set names utf8; ');
  5. $dbh->setattribute (Pdo::attr_errmode, pdo::errmode_exception);
  6. $dbh->begintransaction ();
  7. $DBH,exec ("Insert into ' test ') ' table ' (' Name ', ' age ') VALUES (' Mick ', 22);");
  8. $DBH,exec ("Insert into ' test ') ' table ' (' Name ', ' age ') VALUES (' Lily ', 29);");
  9. $DBH,exec ("Insert into ' test ') ' table ' (' Name ', ' age ') VALUES (' Susan ', 21);");
  10. $dbh->commit ();
  11. } catch (Exception $e) {
  12. $dbh->rollback ();
  13. echo "Failed:".    $e->getmessage ();
  14. }
  15. ?>


PDO Common methods:
Pdo::query () is primarily used for operations (pdostatement) that have logged results returned, especially for select operations.

Pdo::exec () is primarily for operations returned without a result set. such as Insert,update and other operations. Returns the number of affected rows.
Pdo::lastinsertid () returns the last ID of the last insert operation, but note that if you use INSERT into TB (col1,col2) VALUES (V1,V2), (V11,V22): By inserting multiple records at once, Lastinsertid () returns only the ID of the first (V1,V2) insert, not the record ID that was inserted in the last record.
Pdostatement::fetch () is used to get a record. With while to traverse.
Pdostatement::fetchall () is to get all recordsets into one.
Pdostatement::fetchcolumn ([int column_indexnum]) is used for direct access to the column, and the parameter column_indexnum is the 0-based index value in the row of the column, but this method can only get one row at a time. Once executed, jump to the next line. Therefore, it is better to use for direct access to a column, but it is not useful to traverse multiple columns.
Pdostatement::rowcount () is used when using the query ("SELECT ...") method to get the number of records. can also be used in preprocessing. $stmt->rowcount ();
Pdostatement::columncount () is used when using the query ("SELECT ...") method to get the number of columns of a record.

Annotations:
1, pick or fetchall?
Small record set, with fetchall efficiency, reduce the number of retrieval from the database, but for large result sets, with Fetchall to the system brings a great burden. The database is too large to transmit to the web front end and inefficient.
2. Fetch () or Fetchall () has several parameters:
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, can be saved, returns associations and indexes.
$row = $rs->fetchall (PDO::FETCH_ASSOC); The FETCH_ASSOC parameter determines that only the associative array is returned.
$row = $rs->fetchall (pdo::fetch_num); Returns an indexed array
$row = $rs->fetchall (pdo::fetch_obj); If fetch () returns the object, and if it is Fetchall (), returns a two-dimensional array consisting of the object

PHP MySQL PDO use

Related Article

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.