8 tips for PHP and MySQL Development

Source: Internet
Author: User
Tags php error web database

Source: www.freelamp.com
For websites with lamp architecture, I used to focus mostly on installation/configuration, but there are few development stories, because I am rarely engaged in development. The original text of this article also comes from:

Published on the O 'Reilly Network (http://www.oreillynet.com /)
Http://www.oreillynet.com/pub/a/onlamp/2002/04/04/webdb.html

After reading it, I was inspired to solve some problems encountered in the previous development. Therefore, the translation is shared with everyone.

1. Use of arrays in PHP
It is very helpful to use associatively-indexed arrays when operating the database. Let's take a look at the basic number format of array traversal:

<? PHP
$ Temp [0] = "Richmond ";
$ Temp [1] = "Tigers ";
$ Temp [2] = "premiers ";

For ($ x = 0; $ x <count ($ temp); $ X ++)
{
Echo $ temp [$ X];
Echo "";
}
?>

However, the other method is more cost-effective.CodeThe method is:

<? PHP
$ Temp = array ("Richmond", "Tigers", "premiers ");
Foreach ($ temp as $ element)
Echo "$ element ";
?>

Foreach can also output text Subscript:

<? PHP
$ Temp = array ("club" => "Richmond ",
"Nickname" => "Tigers ",
"Aim" => "premiers ");

Foreach ($ temp as $ key => $ value)
Echo "$ key: $ value ";
?>
The PHP manual describes about 50 functions used to process arrays.

2. Add a variable to the PHP string

This is simple:

<? PHP
$ Temp = "hello"
Echo "$ temp world ";
?>

However, it should be noted that, although the following example is not incorrect:
<? PHP
$ Temp = array ("one" => 1, "two" => 2 );
// Output: the first element is 1
Echo "the first element is $ temp [one].";
?>

However, if the echo statement that follows is not caused by double quotation marks, an error is reported. We recommend that you use curly brackets:

<? PHP
$ Temp = array ("one" => 1, "two" => 2 );
Echo "the first element is {$ temp [" one "]}.";
?>

3. Access query results using Correlated Arrays
See the following example:

<? PHP
$ Connection = mysql_connect ("localhost", "Albert", "shhh ");
Mysql_select_db ("winestore", $ connection );

$ Result = mysql_query ("select cust_id, surname,
Firstname from customer ", $ connection );

While ($ ROW = mysql_fetch_array ($ result ))
{
Echo "ID: \ t {$ row [" cust_id "]} \ n ";
Echo "surname \ t {$ row [" surname "]} \ n ";
Echo "First name: \ t {$ row [" firstname "]} \ n ";
}
?>

The mysql_fetch_array () function puts a row of the query result into an array and can be referenced in two ways at the same time. For example, cust_id can be referenced in the following two ways at the same time: $ row ["cust_id"] or $ row [0]. Obviously, the former is much more readable than the latter.

In multi-table join queries, if the names of the two columns are the same, it is best to separate them with aliases:

Select winery. Name as wname,
Region. Name as rname,
From winery, Region
Where winery. region_id = region. region_id;

The column names are referenced as $ row ["wname"] and $ row ["rname"].

When the table name and column name are specified, only the column name is referenced:

Select winery. region_id
From winery

Column Name Reference: $ row ["region_id"].

The reference of the aggregate function is the reference Name:

Select count (*)
From customer;

Column Name Reference: $ row ["count (*)"].

4. Pay attention to common PHP bugs

Common PHP Error Correction problems are:

No page rendered by the web browser when much more is expected
A pop-up dialog stating that the "document contains no data"
A partial page when more is expected

Most of the reasons for these problems are not the logic of the script, but the bug in HTML or the HTML bug generated by the script. For example, the page cannot be refreshed without a close tag such as </table>, </form>, and </frame>. To solve this problem, you can viewSource code.

For pages that are complex and cannot find the cause, you can use W3C page verification.ProgramHttp://validator.w3.org/to analyze.

If no variable is defined, or the definition of the variable is incorrect, the program will become odd. For example, the following endless loop:

<? PHP
For ($ counter = 0; $ counter <10; $ counter ++)
Myfunction ();
?>

The variable $ counter is increasing, while the variable $ counter is always less than 10. Errors of this type can be found by setting a high error report level:

<? PHP
Error_reporting (e_all );

For ($ counter = 0; $ counter <10; $ counter ++)
Myfunction ();
?>

5. Use the header () function to process single part queries

In many web database applications, some features often allow users to click a connection and stay on the current page. I call this "single part query ".

The following is a script called calling. php:

<! Doctype HTML public
"-// W3C // dtd html 4.0 transitional // en"
Http://www.w3.org/TR/html4/loose.dtd>
<HTML>
<Head>
<Title> calling page example </title>
</Head>
<Body>
<A href = "Action. php"> click here! </A>
</Body>
</Html>

When you click the connection above, you can call action. php. The following is the source code of action. php:

<? PHP
// Database functions

// Redirect
Header ("Location: $ http_referer ");
Exit;
?>

There are two common errors to be reminded:
After the header () function is called, an exit statement must be included to stop the script. Otherwise, subsequent Scripts may be output before the header is sent.

A common error in the header () function is:

Warning: cannot add header information-headers already sent...

The Header () function can only be called before HTML output. Therefore, you need to check possible empty lines and spaces before PHP.

6. Reload Problems and Solutions
When I used to write a PHP program, I often encountered a situation where the database was processed once more when the page was refreshed.
Let's take a look at addcust. php:

<? PHP
$ Query = "insert into customer
Set surname = $ surname,
Firstname = $ firstname ";
$ Connection = mysql_connect ("localhost", "Fred", "shhh ");
Mysql_select_db ("winestore", $ connection );
$ Result = mysql_query ($ query, $ connection );
?>
<! Doctype HTML public
"-// W3C // dtd html 4.0 transitional // en"
Http://www.w3.org/TR/html4/loose.dtd>
<HTML>
<Head>
<Title> customer insert </title>
</Head>
<Body>
I 've inserted the customer for you.
</Body>
</Html>
?>
Suppose we use the following connection to use this program:

Http://www.freelamp.com/addcust.php? Surname = Smith & firstname = Fred

If this request is submitted only once, OK will not be a problem, but if you refresh multiple times, you will have multiple records inserted.
This problem can be solved through the header () function: the new version of addcust. php is as follows:

<? PHP
$ Query = "insert into customer
Set surname = $ surname,
Firstname = $ firstname ";
$ Connection = mysql_connect ("localhost", "Fred", "shhh ");
Mysql_select_db ("winestore", $ connection );
$ Result = mysql_query ($ query, $ connection );
Header ("Location: cust_receipt.php ");
?>
This script redirects the browser to a new page: cust_receipt.php:

<! Doctype HTML public
"-// W3C // dtd html 4.0 transitional // en"
Http://www.w3.org/TR/html4/loose.dtd>
<HTML>
<Head>
<Title> customer insert </title>
</Head>
<Body>
I 've inserted the customer for you.
</Body>
</Html>
In this way, the original page continues to refresh without any side effects.

7. Use locks to improve application performance
If we want to run a report urgently, we can apply a write lock to the table to prevent reading/writing by others to improve the processing speed of the table.

8. Use mysql_unbuffered_query () to develop a quick script.
This function can be used to replace the mysql_query () function. The main difference is that mysql_unbuffered_query () returns immediately after the query is executed, without waiting or locking the database.

but the number of returned rows cannot be checked using the mysql_num_rows () function, because the size of the output result set is small and unknown.

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.