Expose five 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 data in many ways
Expose five common database problems in PHP applications-including database pattern design, database access and use of database business logic code-and their solutions.
If onlyOne typeThe correct way to use the database ......
You can create database design, database access, and database-based PHP business logic code in many ways, but it generally ends with an error. This article describes the five common problems in the PHP code for database design and database access, and how to fix these problems.
Question 1: use MySQL directly
A common problem is the direct use of older PHP code.mysql_
Function to access the database. Listing 1 shows how to directly access the database.
Listing 1. Access/get. php
Note thatmysql_connect
Function to access the database. Pay attention to the query, where the string connection is used to add to the query$name
Parameters.
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®DB2®, MySQL, PostgreSQL, or any other database you want to connect.
Another benefit of using the pear db module and the PDO abstraction layer is that you can use?
Operator. This makes SQL easier to maintain and protects your applications from SQL injection attacks.
The alternative code for using pear db is as follows.
Listing 2. Access/get_good.php
getMessage()); } $res = $db->query( 'SELECT id FROM users WHERE login=?', array( $name ) ); $id = null; while( $res->fetchInto( $row ) ) { $id = $row[0]; } return $id;}var_dump( get_user_id( 'jack' ) );?> |
Note that all the places that directly use MySQL are eliminated, only$dsn
Except for the database connection strings in. In addition, we use?
Use operators in SQL$name
Variable. Then, the queried data passes throughquery()
Thearray
Sent in.