PHP database FAQs page 1/3

Source: Internet
Author: User
Tags dsn ibm db2 pear php database

If there is only one way to use the database, it is correct ......

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 that older PHP Code directly uses the mysql _ function to access the database. Listing 1 shows how to directly access the database.

Reference content is as follows:

<? 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 '));
?>

Listing 1. Access/get. php
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 run on IBM DB2, MySQL, PostgreSQL, or any other database you want to connect to without too much adjustment.

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.

The alternative code for using pear db is as follows.

Reference content is as follows:

<? 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 '));
?>

Listing 2. Access/get_good.php
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.

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.

Copy codeThe Code is as follows: drop table if exists users;
Create table users (
Id MEDIUMINT,
Login TEXT,
Password TEXT
);
Insert into users VALUES (1, 'jack', 'pass ');
Insert into users VALUES (2, 'job', 'pass ');
Insert into users VALUES (1, 'Jane ', 'pass ');

Listing 3. Badid. SQL

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.Copy codeThe Code is as follows: <? Php
Require_once ("DB. php ");

Function add_user ($ name, $ pass)
{
$ Rows = array ();

$ Dsn = 'mysql: // root: password @ localhost/bad_badid ';
$ Db = & DB: Connect ($ dsn, array ());
If (PEAR: isError ($ db) {die ($ db-> getMessage ());}

$ Res = $ db-> query ("SELECT max (id) FROM users ");
$ Id = null;
While ($ res-> fetchInto ($ row) {$ id = $ row [0];}

$ Id + = 1;

$ Something = $ db-> prepare ("insert into users VALUES (?,?,?) ");
$ Db-> execute ($ th, array ($ id, $ name, $ pass ));

Return $ id;
}

$ Id = add_user ('Jerry ', 'pass ');

Var_dump ($ id );
?>

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. The updated mode is as follows.Copy codeThe Code is as follows: drop table if exists users;
Create table users (
Id mediumint not null AUTO_INCREMENT,
Login text not null,
Password text not null,
Primary key (id)
);

Insert into users VALUES (null, 'jack', 'pass ');
Insert into users VALUES (null, 'job', 'pass ');
Insert into users VALUES (null, 'Jane ', 'pass ');

Listing 5. Goodid. php

The not null flag is added to indicate that the field must NOT be blank. We also added the AUTO_INCREMENT flag to indicate that the field is automatically incremental, and added the primary key flag to indicate that the field is an id. These changes speed up. Listing 6 shows the updated PHP code, which inserts users into the table.Copy codeThe Code is as follows: <? Php
Require_once ("DB. php ");

Function add_user ($ name, $ pass)
{
$ Dsn = 'mysql: // root: password @ localhost/good_genid ';
$ Db = & DB: Connect ($ dsn, array ());
If (PEAR: isError ($ db) {die ($ db-> getMessage ());}

$ Something = $ db-> prepare ("insert into users VALUES (null ,?,?) ");
$ Db-> execute ($ th, array ($ name, $ pass ));

$ Res = $ db-> query ("SELECT last_insert_id ()");
$ Id = null;
While ($ res-> fetchInto ($ row) {$ id = $ row [0];}

Return $ id;
}

$ Id = add_user ('Jerry ', 'pass ');

Var_dump ($ id );
?>

Listing 6. Add_user_good.php

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.