Common PHP Database Solutions _php Tutorials

Source: Internet
Author: User
We encounter a lot of problems when using PHP to connect to a database, and this article exposes common database problems in PHP applications-including database schema design, database access, and business logic code that uses the database-and their solutions. If only one way to use the database is correct. You can create PHP database design, database access, and database-based PHP business logic code in a number of ways, but in the end it usually ends in error. This article explains the five common problems that occur in the database design and the PHP code that accesses the database, and how to fix them when they encounter these problems.

PHP database Problem 1: using MySQL directly

A common problem is that older PHP code uses the MYSQL_ function directly to access the database. Listing 1 shows how to access the database directly.

Listing 1. access/get.php

 
 
  1. function get_user_id ($name)
  2. {
  3. $ DB = mysql_connect (' localhost ', ' root ', ' password ');
  4. mysql_select_db (' users ');
  5. $ Res = mysql_query ("Select ID from users WHERE login='". $name. "' " );
  6. While ($row = mysql_fetch_array($res)) {$id = $ ROW[0]; }
  7. return $id;
  8. }
  9. Var_dump (get_user_id (' Jack '));
  10. ? >

Note The Mysql_connect function is used to access the database. Also note the query, which uses a string connection to add $name parameters to the query. There are two good alternatives to this technique: the PEAR DB module and the PHP Data Objects (PDO) class. Both provide abstraction from a specific database selection. So, your code doesn't need to be too much tuned for IBM? Run on DB2, MySQL, PostgreSQL, or any other database you want to connect to. Another value of using the PEAR DB module and the PDO abstraction layer is that you can use it in SQL statements. Operator. Doing so makes SQL easier to maintain and can protect your application from SQL injection attacks.

Listing 2. access/get_good.php

 
 
  1. Require_once ("db.php");
  2. function get_user_id ($name)
  3. {
  4. $ DSN = ' Mysql://root:password@localhost/users ' ;
  5. $ DB =& db::connect ($DSN, Array ());
  6. if (Pear::iserror ($db)) {die ($db->getmessage ());}
  7. $ Res = $db->query (' SELECT ID from users WHERE login=? ', array ($name));
  8. $ ID = NULL ;
  9. While ($res->fetchinto ($row)) {$id = $row [0];}
  10. return $id;
  11. }
  12. Var_dump (get_user_id (' Jack '));
  13. ? >

Note that all the places that are used directly to MySQL are eliminated, except for the database connection string in the $dsn. In addition, we pass? operator to use $name variable in SQL. The queried data is then sent in through an array at the end of the query () method.

PHP Database Issue 2: Do not use the auto-increment feature

Like most modern databases, MySQL can create an AutoIncrement unique identifier on a per-record basis. In addition, we will still see the code that runs a SELECT statement first to find the maximum ID, then adds 1 to the ID and finds a new record. Listing 3 shows an example of a bad pattern.

Listing 3. Badid.sql

 
  
  
  1. DROP TABLE IF EXISTS users;
  2. CREATE TABLE Users (
  3. ID Mediumint,
  4. Login TEXT,
  5. Password TEXT
  6. );
  7. INSERT into Users VALUES (1, ' Jack ', ' Pass ');
  8. INSERT into Users VALUES (2, ' Joan ', ' Pass ');

The ID field here is simply specified as an integer. So, although it should be unique, we can add any value, as shown in several INSERT statements following the CREATE statement. Listing 4 shows the PHP code that adds the user to this type of pattern.

Listing 4. add_user.php

 
 
  1. Require_once ("db.php");
  2. function Add_user ($name, $pass)
  3. {
  4. $ rows = Array ();
  5. $ DSN = ' Mysql://root:password@localhost/bad_badid ' ;
  6. $ DB =& db::connect ($DSN, Array ());
  7. if (Pear::iserror ($db)) {die ($db->getmessage ());}
  8. $ Res = $db->query ("SELECT Max (ID) from users");
  9. $ ID = NULL ;
  10. While ($res->fetchinto ($row)) {$id = $row [0];}
  11. $id + = 1;
  12. $ sth = $db->prepare ("INSERT into Users VALUES (?,?,?)");
  13. $db->execute ($sth, Array ($id, $name, $pass));
  14. return $id;
  15. }
  16. $ ID = Add_user (' Jerry ', ' Pass ');
  17. Var_dump ($id);
  18. ? >

The code in add_user.php first executes a query to find the maximum value of the ID. The file then runs an INSERT statement with the ID value plus 1. The code will fail in a race condition on a heavily loaded server. In addition, it is inefficient. So what is the alternative? Use the auto-increment feature in MySQL to automatically create a unique ID for each insert.


http://www.bkjia.com/PHPjc/446456.html www.bkjia.com true http://www.bkjia.com/PHPjc/446456.html techarticle we encounter a lot of problems when using PHP to connect to a database, and this article exposes common database problems in PHP applications-including database schema design, database visits ...

  • 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.