How to Use PHP to access the MySQL database from the Web

Source: Internet
Author: User
Tags web database
I. Working Principles of Web database architecture 1. A user's browser sends an HTTP request to request a specific Web page. on this page, the form is submitted to the php script file (for example, results. php) Processing 2. the Web server receives the results. after a php page request is sent, retrieve the file and pass it to the PHP engine for processing. 3. PHP Engine

I. Working Principles of Web database architecture 1. A user's browser sends an HTTP request to request a specific Web page. on this page, the form is submitted to the php script file (for example, results. php) Processing 2. the Web server receives the results. after a php page request is sent, retrieve the file and pass it to the PHP engine for processing. 3. PHP Engine

I. Working Principles of Web database architecture

1. A user's browser sends an HTTP request to request a specific Web page and submits the form from this page to the php script file (for example, results. php) for processing.

2. After receiving a request to the results. php page, the Web server retrieves the file and passes it to the PHP engine for processing.

3. the php engine starts parsing scripts. The script mainly includes commands for connecting to the database and executing the query. PHP starts a connection to the MySQL server and sends an appropriate query to the server.

4. When the MySQL server receives a database query request, it starts to process the query and returns the query result to the PHP engine.

5. After the PHP engine runs the script, return the HTML to the Web server.

6. The Web server then returns HTML to the client browser, and the user can see the response result page.

2. Basic Steps for querying databases from the Web

1. check and filter data from the user. First, we will filter the blank characters that the user may accidentally enter at the start or end of the search condition, which is implemented using the trim () function. The reason why we are so troublesome to check user input data is to prevent multiple interfaces from connecting to the database, because the user enters from different interfaces, which may cause security problems.

Then, when preparing to use any data entered by the user, filter some control characters as well. When the user inputs data to the database, the data must be escaped ,, in this case, the stolen functions include the addslashes () function, the stripslashes () function, and the get_magic_qutoes_gpc () function. The addslashes () function requires a backslash before certain characters for database query statements. The stripslashes () function removes the backslash character from the string. get_magic_qutoes_gpc () function magic adds the Escape Character "" to get the magic_quotes_runtime setting of the current activity configuration. If the magic quotation marks are disabled during runtime, 0 is returned; otherwise, 1 is returned. We can also use htmispecialchars () to encode special characters in HTML. The htmispecialchars () function converts some predefined characters into HTML entities. [the predefined characters are: & (and) becomes & "(double quotation marks) becomes" '(single quotation marks) becomes' <(less than) becomes <> (greater than) becomes>]

2. Establish a connection to the appropriate database. PHP provides the function library mysqli (I indicates improvement) for connecting to MySQL ).

When using the mysqli function library in PHP, you can use object-oriented or process-oriented Syntax:

1. object-oriented, @ $ db = new mysqli ('hostname', 'username', 'Password', 'dbname'); returns an object

2. process-oriented: @ $ db = mysqli_connect ('hostname', 'username', 'Password', 'dbname'); a resource is returned, which indicates the database connection, if you use the procedure method, you must pass this resource to all other functions of mysqli. This is very similar to processing functions.

Most functions of mysqli have object-oriented interfaces and process interfaces. The difference between them is that the function name of the Process version starts with mysqli _ and the resource handle obtained by the mysqli_connect () function must be passed in. For this rule, data connection is an exception because it is created by the constructor of the mysqli object. Therefore, you must check the connection attempt. The mysqli_connect_errno () function returns an error code when a connection error occurs. If the connection is successful, 0 is returned.

Note:

When connected to the database, the Meeting error blocker @ is usually used as the first containing code. In this way, you can skillfully handle any errors or exceptions. In addition, MySQK limits the number of connections to the database at the same time. The MySQLi parameter max_connections determines the number of simultaneous connections. This parameter and the related Apache parameter MaxClients are used to tell the server to reject new connection requests, this ensures that system resources are no longer requested or used when the system is busy or when the system is paralyzed. To set the MaxClients parameter in Apache, edit the httpd. conf file in the system. To set the max_connections parameter for MySQLi, You can edit the file my. conf.

Select the database to use: use the use dbname command on the MySQL command line; use $ db-> select_db (dbname); or mysqli_select_db (db_resource, dbname) in php ).

3. to query a database, you must first construct a query statement: $ query = "select from user"; then run $ result = $ db-> query ($ query ); or $ result = mysqli_query ($ db, $ query). The object-oriented version returns a result object, and the procedural version returns a result resource. No matter which method saves the result in the $ result variable, it will be used after work. If the function fails to run, false is returned.

4. Obtain the query result using different functions to retrieve the query result from the result object or identifier in different ways. The result object or identifier is the key to accessing the returned row of the query.

We usually need to obtain the number of rows in the result set, and use the mysqli_fetch_assoc () function.

Number of returned rows: $ num_results = $ result-> num_rows; (the number of rows is saved in the num_rows member variable of the object) or $ num_results = mysqli_num_rows ($ result );

Then, traverse each row in a loop and call $ row = $ result-> fectch_assoc (); or $ row = mysqli_fetch_assoc ($ result); to return information about the row. If the row is returned by an object, each keyword is an attribute name, and each value is the corresponding value in the attribute. If the row is returned by a resource, an array is returned.

There are other methods to get results from the result identifier, such as using $ row = $ result-> fecth_row ($ result); or $ row = mysqli_fetch_row ($ result ); you can also use $ row = $ result-> fecth_object (); or $ row = mysqli_fecth_object ($ result ); jiang and his entourage go back to an object.

5. first release the result set from database disconnection: $ result-> free (); or mysqli_free_result ($ result); then close the database connection: $ db-> close () or mysqli_close ($ db); strictly speaking, this is not required because they will be automatically disabled when the script is executed.

3. Use the Prepared statement

The mysqli function library supports the use of prepared statements. They can speed up the execution of a large number of identical queries with different data, or be immune from the SQL injection style (injection-stytle-attacks.

The basic idea of the prepared statement is to send a query template to MySQL and then send data separately. We can send a large amount of identical data to the same prepared statement. This feature is very useful for batch insert operations.

The following steps are generally used:

1. Create a template. Example: $ query = "insert into user values (?,?,?,?) ";

2. Use the prepared statement to construct a statement object or resources to be used for actual processing. $ Stmt = $ db-> prepare ($ query); or mysqli_stmt_prepare ($ query );

3. Call $ stmt-> bind_param ("sssd", $ str1, $ str3, $ str3, $ int4) or mysqli_stmt_bind_param ("sssd", $ str1, $ str3, $ str3, $ int4) tells php that the variables should be replaced by question marks. The first parameter is a formatted string followed by the variable to be replaced.

3. Call the $ stmt-> execute () or mysqli_stmt_execute () function to run the query statement.

For select-type queries, you can use the $ stmt-> bind_result () or mysqli_stmt_bind_result () function to provide a list of variables to be filled in the result column, and then call $ stmt-> fetch () each time () or mysqli_stmt_fetch () function, the values of the next row in the result set will be filled in these bind variables.

4. Use other interfaces for PHP interaction with the database

PHP supports functions connected to many different databases, including Oracle, Microsoft SQL Server, and PostgreSQL. Generally, the basic principles for connecting and querying these data sets are the same, and the names of some functions may be different. If you want to use a special database that PHP does not support, you can use the conventional ODBC function.

ODBC indicates an open database connection, which is the standard for database connection. ODBC only has the priority function of any function set. If it is required to be compatible with all databases, it cannot use any special functions of the database.

In addition to the function library that comes with PHP, some database abstract classes that can be used, such as MDB2, allow the same function name for different database types. However, you must install the abstraction layer in advance, such as the PEAR MDB2 abstraction layer.

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.