PHP MySQL connection method PDO usage

Source: Internet
Author: User
Tags php mysql rowcount
  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 ' =:p assword";
  6. $sql = "INSERT into ' user ' (' login ', ' password ') VALUES (: Login,:p assword)"; $stmt = $dbh->prepare ($sql); $stmt->execute (': Login ' = ' kevin2 ', ':p assword ' = ') ');
  7. echo $DBH->lastinsertid ();
  8. /* Modify */
  9. $sql = "UPDATE ' user ' SET ' password ' =:p assword WHERE ' user_id ' =:userid";
  10. $stmt = $dbh->prepare ($sql);
  11. $stmt->execute (Array (': userId ' = ' 7 ', ':p assword ' = ' 4607e782c4d86fd5364d7e4508bb10d9 '));
  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. ?>
Copy Code

1. Establish the connection

    1. $DBH =newpdo (' mysql:host=localhost;port=3306; Dbname=test ', $user, $pass, Array (
    2. Pdo::attr_persistent=>true
    3. ));
    4. ?>
Copy Code

Persistent link Pdo::attr_persistent=>true

2, catch error

    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 Connection
    6. }catch (pdoexception$e) {
    7. Print "error!:". $e->getmessage (). "
      ";
    8. Die ();
    9. }
    10. ?>
Copy Code

3,PDO transactions

    1. try{
    2. $DBH->setattribute (pdo::attr_errmode,pdo::errmode_exception);
    3. $DBH->begintransaction ();//Open transaction
    4. $DBH->exec ("Insertintostaff (Id,first,last) VALUES (+, ' Joe ', ' Bloggs ')");
    5. $DBH->exec ("Insertintosalarychange (id,amount,changedate)
    6. VALUES (23,50000,now ()) ");
    7. $DBH->commit ();//Commit a transaction
    8. }catch (exception$e) {
    9. $DBH->rollback ();//Error rollback
    10. echo "Failed:". $e->getmessage ();
    11. }
    12. ?>
Copy Code

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::P aram_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. ?>
Copy Code

1, using Query ()

    1. $DBH->query ($sql); When the $sql variable can be used $dbh->quote ($params); Escaping the data of a string
    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. ?>
Copy Code

2, using prepare, Bindparam and execute [recommended, can also be added, modified, deleted]

    1. $DBH->prepare ($sql); Produced a Pdostatement object.
    2. Pdostatement->bindparam ()
    3. Pdostatement->execute ();//You can put the corresponding variable of the binding here
    4. ?>
Copy Code

3. PHP PDO Transaction Example

    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. ?>
Copy Code
  • 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.