Analysis and introduction to common PHP database solutions-PHP Tutorial

Source: Internet
Author: User
Tags php database
Analyze and introduce common PHP database solutions. We will encounter many problems when using PHP to connect to the database. This article exposes common database problems in PHP applications, including database pattern design and database access. PHPYou may encounter many problems when connecting to the database, this article exposes common database problems in PHP applications-including database pattern design, database access and use of database business logic code-and their solutions. If there is only one way to use the database, it is correct.

You can create PHP database design, database access, and database-based PHP business logic code in many ways, but it generally ends with errors. This article describes the five common problems in the PHP code for database design and database access, and how to fix these problems.

PHP database Question 1: use MySQL directly

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

Listing 1. Access/get. php

 
 
  1. <?php
  2. function get_user_id( $name )
  3. {
  4. $db = mysql_connect( 'localhost', 'root', 'password' );
  5. mysql_select_db( 'users' );
  6. $res = mysql_query( "SELECT id FROM users WHERE login='".$name."'" );
  7. while( $row = mysql_fetch_array( $res ) ) { $id = $row[0]; }
  8. return $id;
  9. }
  10. var_dump( get_user_id( 'jack' ) );
  11. ?>

Note that the mysql_connect function is used to access the database. Pay attention to the query. use string connection to add the $ name parameter to the query. This technology has two good alternatives: the pear db module and the PHP Data Objects (PDO) class. Both provide abstraction from the choice of a specific database. Therefore, your code can be stored in IBM without too many adjustments? DB2? , MySQL, PostgreSQL, or any other database you want to connect. Another value of using the pear db module and the PDO abstraction layer is that you can use it in SQL statements? Operator. This makes SQL easier to maintain and protects your applications from SQL injection attacks.

Listing 2. Access/get_good.php

 
 
  1. <?php
  2. require_once("DB.php");
  3. function get_user_id( $name )
  4. {
  5. $dsn = 'mysql://root:password@localhost/users';
  6. $db =& DB::Connect( $dsn, array() );
  7. if (PEAR::isError($db)) { die($db->getMessage()); }
  8. $res = $db->query( 'SELECT id FROM users WHERE login=?',array( $name ) );
  9. $id = null;
  10. while( $res->fetchInto( $row ) ) { $id = $row[0]; }
  11. return $id;
  12. }
  13. var_dump( get_user_id( 'jack' ) );
  14. ?>

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

PHP database Question 2: Do not use the auto increment function

Like most modern databases, MySQL can create automatic incremental unique identifiers based on each record. In addition, we will still see the code, that is, first run a SELECT statement to find the largest id, then add this id to 1, and find a new record. Listing 3 shows an example of bad mode.

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' );
  9. INSERT INTO users VALUES ( 1, 'jane', 'pass' );

Here, the id field is simply specified as an integer. Therefore, although it should be unique, we can add any value, as shown in the INSERT statements following the CREATE statement. Listing 4 shows the PHP code that adds users to this type of mode.

Listing 4. Add_user.php

The code in add_user.php first executes a query to find the maximum value of the id. Then, the file adds 1 to the id value to run an INSERT statement. This code fails in the race condition on a server with heavy loads. In addition, it is also inefficient. So what is the alternative? Use the automatic incremental feature in MySQL to automatically create a unique ID for each insert.

 
 
  1. <?php
  2. require_once("DB.php");
  3. function add_user( $name, $pass )
  4. {
  5. $rows = array();
  6. $dsn = 'mysql://root:password@localhost/bad_badid';
  7. $db =& DB::Connect( $dsn, array() );
  8. if (PEAR::isError($db)) { die($db->getMessage()); }
  9. $res = $db->query( "SELECT max(id) FROM users" );
  10. $id = null;
  11. while( $res->fetchInto( $row ) ) { $id = $row[0]; }
  12. $id += 1;
  13. $sth = $db->prepare( "INSERT INTO users VALUES(?,?,?)" );
  14. $db->execute( $sth, array( $id, $name, $pass ) );
  15. return $id;
  16. }
  17. $id = add_user( 'jerry', 'pass' );
  18. var_dump( $id );
  19. ?>

We hope that this article will give you a better understanding of the PHP database solution.


PHP will encounter many problems when connecting to the database. This article exposes common database problems in PHP applications, including database pattern design and database access...

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.