If there is only one way to use
Databaseis correct, there are many ways you can create database design, database access, and database-based
PHPBusiness logic code, 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.
Issue 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
-
- function get_user_id ( $name )
- {
- $db = mysql_connect ( ' localhost ', ' root ', ' password ' );
- mysql_select_db ( ' users ' );
- $res = mysql_query ( "SELECT ID from Users WHERE login= '". $name . "'" );
- while ( $row = mysql_fetch_array ( $res )) { $id =
$row[0];}
- return $id;
- }
- Var_dump (get_user_id ( ' Jack ' ));
- ?>
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. As a result, your code doesn't need to be too much tuned to run on ibm®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.
The alternative code that uses PEAR DB is shown below.
Listing 2. access/get_good.php
-
- require_once ("db.php");
- function get_user_id ( $name )
- {
- $dsn = ' Mysql://root:password@localhost/users ' ;
- $db =& db::connect ( $dsn, array());
- if (Pear::iserror ($db)) { die($db 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 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.
1
http://www.bkjia.com/PHPjc/445827.html www.bkjia.com true http://www.bkjia.com/PHPjc/445827.html techarticle if only one way to use the database is correct, you can create database design, database access, and database-based PHP business logic code in a number of ways, but ultimately ...