PHP + MYSQL dynamic web page programming error correction guide _ MySQL

Source: Internet
Author: User
Tags parse error mysql command line metabase
PHP + MYSQL dynamic WEB page programming error correction guide in WEB programming, the role of the database has become increasingly important. When talking about databases, PHP has very powerful database support functions. from FileMaker to Oracle, PHP can be seamlessly connected to almost all database systems. For the convenience of this article, we will take MySQL as an example. However, it is also applicable to other database applications.

The following statements are generally required for database operations using PHP:


   $ Host = "localhost ";
$ MySQL_UserName = "root ";
$ MySQL_UserPass = "password ";
$ MySQL_Database = "db ";
$ Query = "SELECT * FROM domain ";
Mysql_connect ($ Host, $ MySQL_UserName, $ MySQL_UserPass );
Mysql_select_db ($ MySQL_Database );
$ Result_ID = mysql_query ($ Query );
While ($ Result = mysql_fetch_row ($ Result_ID )){
Print ------------------
;
Print "$ Result [0]
";
Print "$ Result [1]
";
Print "$ Result [2]
";
Print "$ Result [3]
";
Print -------------------
;
}?>


The basic steps include establishing a connection to the MySQL database, selecting the database operation object, and then executing the query statement. In general, the prompts for errors in the above process can be described in a more accurate and detailed manner. For example, the "Connection failed due to a bad username" error report clearly indicates that the Connection to the database fails due to a user name error.

We can use the return values of these functions mentioned above to reduce unnecessary troubles. For example, the mysql_connect function returns a Connection ID when the connection is successful. if the connection fails, an error is returned. In this regard, we can make the following use:

If (! Mysql_connect ('localhost', 'root', 'password ')){
Print "Cannot connect to MySQL
";
Exit;
}


When there is a problem with the database connection, we can output an error prompt and terminate the program execution. In the long run, this is a very good precaution. In this way, we re-compile the script as follows:

   $ Host = "localhost ";
$ MySQL_UserName = "root ";
$ MySQL_UserPass = "password ";
$ MySQL_Datab = "db ";
$ Query = "SELECT * FROM domain ";
If (! Mysql_connect ($ Host, $ MySQL_UserName, $ MySQL_UserPass )){
Print "Cannot connect to MySQL:". mysql_error ();
Exit;
}
If (! Mysql_select_db ($ MySQL_Database )){
Print "Cannot select db
";
Exit;
}
If (! $ Result_ID = mysql_query ($ Query )){
Print "Query Error:". mysql_error ();
Exit;
}
While ($ Result = mysql_fetch_row ($ Result_ID )){
Print ------------------
;
Print "$ Result [0]
";
Print "$ Result [1]
";
Print "$ Result [2]
";
Print "$ Result [3]
";
Print -------------------
;
}?>

In this way, when a program encounters a problem, we can immediately find the root cause of the error, so as to be targeted.


Next, we can query the database. However, many times, when we run the compiled query statement, we do not get any returned data. What is an error? The best solution is to assign the SQL statement to a variable, for example:


   ....
$ SQL = "SELECT * FROM $ TableName WHERE $ ColumnName> $ Limit ";
$ Result_ID = mysql_query ($ QUERY );
...?>

Then, when a problem occurs, run the "print" or "echo" command to display the statement. Check whether the spelling of $ ColumnName and $ Limit is correct and whether new variables are created unintentionally. The output display method can easily locate and solve spelling errors. But what if no obvious error is found after the SQL statement is displayed? Here we can paste the output statement into a command line tool like the Mysql command line interface to see if data can be returned. If the problem persists, check the user permissions of the account.

Today, we can use many free classes to perform most database operations. PHP Classes (http://phpclasses.upperdesign.com/) has a lot of related information for interested users to refer. MetaBase can provide query and management independent of a database system. If you are using several different database systems at the same time, or want your programs to be transplanted to other database platforms, pay attention to the use of MetaBase.

Note: At last, we will summarize some of the issues that should be paid attention to during PHP programming, hoping to help you.


1. check the symbols (), [], and {} to see if they are paired.
2. check the string. Note that if you want to use "" again in "", you must use the escape character "/".
3. check whether the reserved keywords are correctly spelled. For example, change myslq_num_rows () to mysql_num_rows.
4. check whether the program syntax is correct against the PHP user manual (www.php.net/manual.
5. if you use global variables in a function, do not forget to declare the variables.
6. if you want to use the setCookie () function to set Cookie information, make sure that no characters are output before this, including 7. if the database query operation fails, use echo or print to write the query statement and check whether the syntax is correct. pay special attention to the variables in the statement.
8. if the SQL statement has no obvious problem, try to use the command line interface provided by the database system.
9. if the problem persists, check whether the database has sufficient access permissions.
10. if the error "can't redeclare foo ()" occurs, it indicates that the user may reference the same file twice. You can use the include_once () function to avoid this problem.
11. be case sensitive. For example, $ Foo and $ FOO are two different variables.
12. pay attention to the correct format of the array. For example, $ this-> $ foo () and $ this-> $ variable should be changed to $ this-> foo () and $ this-> variable, respectively.

The use of semicolons is just as we usually have to end each sentence at the end of the article, PHP requires that each statement in the program must end with a semicolon. This is the most basic syntax rule, but it is also the most prone to problems. When writing a program, we seldom check whether a semicolon is missing in a row or line, but once there is any negligence, the parsing program will issue an error report immediately. Sometimes, the report may contain the number of problematic statements.


   $ Output = "Hello World ";
Echo $ Output
$ Other = "Blah ";
Print $ SomeMoreText;
?>

A semicolon is missing at the end of the second line "echo $ Output" of the above code. if you execute this script, the following error message will be generated:


Parse error: parse error, expecting '','' or '';'' in/usr/local/apache/htdocs/test. although the php on line 8 report points out the cause of the error, that is, the comma "," or semicolon ";" is missing, but the problematic statement is set to the eighth line. Because this code is very simple, we can easily find the real error. However, if the program is very complex, it is difficult to find out the errors smoothly.


Based on my previous experience, the following methods are recommended:

If the statements in the error report do not have obvious problems, you can check whether other command lines (excluding comment lines) that are located before the statement are correct. If no error is found, comment out the statement line in the report (add "//" or "#" at the beginning of the statement line) you can also change to other statements that can ensure that there is no problem at all. Then run the program again. if the error prompt still points to the same line, it indicates that the problematic statement should be located before the commented-out statement line. Check each line of commands in front of each position one by one according to the above method until the error message changes. At this time, we have successfully dug out the real culprit.


Variables are different from other programming languages that require users to explicitly declare variables. PHP allows users to automatically use all variables without having to declare them in advance. Misspelling of variable names has become a major problem for PHP users.

   Function Combine ($ FirstHalf, $ SecondHalf)
{
$ Combined_String = $ FirstHalf. $ SecondHalf;
Return $ Combined_String;
}
$ FirstString = "WDVL -";
$ SecondString = "inclustrated Encyclopedia ";
$ Combine_Result = Combine ($ FirstString, $ SecondString );
Print $ Combined_Result;
?>

When we run the above script, we will see the error message because the program does not return any data. Here, we chose a very intuitive example to better illustrate the problem. In reality, sometimes the problem is not that simple. I believe everyone has found the cause of the problem, that is, the variable name "$ Combined_Result" in "print $ Combined_Result;" should be changed to "$ Combine_Result ".
In fact, any spelling error in the script will cause the same problem. If you suspect that your program has a spelling mistake, a good check method is to display text information before and after the variable. For example:

Print "The Combined Result is: |". $ Combined_Result. "| ";


The result is as follows:

The Combined Result is: |

There is no content between the two MPs queue symbols "|. In this way, we can find the problematic variable in the program.


Next, we will illustrate a more complex example.

At present, many network applications need to verify the user's identity. The simplest implementation script is as follows:

$ Password = "Secret ";
$ Name = "admin ";
Function VerifyPassword ($ UserPassword, $ UserName ){
If ($ Password = $ UserPassword & $ Name = $ UserName ){
Return 1;
}
Else {return 0 ;}
}
If (VerifyPassword ("foo1ish", "admin ")){
Print "The Password is correct ";
}
Else {
Print "I'm sorry, the password is incorrect ";
}
?>

Although the incorrect password is entered when the VerifyPassword function is called in the above script, the following results will still be generated after the program runs:

The Password is correct

The problem may occur anywhere. let's use the exclusion method for one-to-one checks. First, it is difficult to determine whether the "if" condition statement at the end of the script is correct. Although it seems that there is no problem, to ensure that the program is correct, we cannot let go of any link. Therefore, we comment out the condition statement and output the VerifyPassword () function according to the method described above. The details are as follows:


$ Password = "Secret ";
$ Name = "admin ";
Function VerifyPassword ($ UserPassword, $ UserName ){
If ($ Password = $ UserPassword & $ Name = $ UserName ){
Return 1;
}
Else {return 0 ;}
}
Print "The result of VerifyPassword () is :";
Print VerifyPassword ("foo1ish", "admin ");
/* If (VerifyPassword ("foo1ish", "admin ")){
Print "The Password is correct ";
}
Else {
Print "I'm sorry, the password is incorrect ";
}*/
?>

Because we use the wrong password, the result should be 0. However, after the program runs, we find that the actual results are as follows:


The result of VerifyPassword () is: 1

In this way, we can see that the problem occurs on the VerifyPassword () function. After checking the function, we suspect that the problem may occur in the "if" statement. Therefore, we shield the conditional statements in the VerifyPassword () function and output them as follows:


Print "UserPassword => $ UserPassword, Password => $ Password ,";
Print "Password = UserPassword =>". (int) ($ Password = $ UserPassword)."
";
Print "UserName => $ UserName, Name => $ Name ,";
Print "Name = UserName =>". (int) ($ Name = $ UserName)."
";

(Note: We use the (int) ($ Password = $ UserPassword) statement to convert the comparison result to an integer 0 or 1)

The actual output result after the program is modified is as follows:

UserPassword => foo1ish, Password =>, Password = UserPassword => 0
UserName => admin, Name =>, Name = UserName => 1
I'm sorry, the password is incorrect

Here, we can clearly see that both the Password and Name variables are null values, so it is no wonder that the statement does not work.

Why is $ Password null? At the beginning of the program, we have explicitly assigned values to the $ Password variable, but the original variable value cannot be included in the VerifyPassword () function. Looking back at the PHP language's variable scope, we can immediately find the cause of the problem, that is, if you want to use a variable in a function, you must declare the variable as a global variable. After knowing the root cause of the error, we add the following statement to the first line of the VerifyPassword () function and re-run the program:

Global $ Password, $ Name;


The program running result is as follows:

UserPassword => foo1ish, Password => Secret, Password = UserPassword => 0
UserName => admin, Name => admin, Name = UserName => 1
The Password is correct

Why? We should be prompted for incorrect passwords. After checking the program again, we finally found that we misuse the logical operator "=" to "=", so that we assigned the value of the $ UserPassword variable to the $ Password variable. After the last two errors are corrected, the completed procedure is as follows:


<?
$ Password = "Secret ";
$ Name = "admin ";
Function VerifyPassword ($ UserPassword, $ UserName ){
Global $ Password, $ Name;
If ($ Password = $ UserPassword & $ Name = $ UserName ){
Return 1;
}
Else {return 0 ;}
}
If (VerifyPassword ("foo1ish", "admin ")){
Print "The Password is correct ";
}
Else {
Print "I'm sorry, the password is incorrect ";
}
?>

The execution result is as follows:


I'm sorry, the password is incorrect.


Enter the correct password and run the command again. The following result is displayed:

The Password is correct

In this way, we can find and solve the problem. I hope you can learn some methods and ideas for finding errors from the above introduction.


With regard to the WEB programming of databases, the role of databases has become increasingly important. When talking about databases, PHP has very powerful database support functions. from FileMaker to Oracle, PHP can be seamlessly connected to almost all database systems. For the convenience of this article, we will take MySQL as an example. However, it is also applicable to other database applications.


The following statements are generally required for database operations using PHP:

   $ Host = "localhost ";
$ MySQL_UserName = "root ";
$ MySQL_UserPass = "password ";
$ MySQL_Database = "db ";
$ Query = "SELECT * FROM domain ";
Mysql_connect ($ Host, $ MySQL_UserName, $ MySQL_UserPass );
Mysql_select_db ($ MySQL_Database );
$ Result_ID = mysql_query ($ Query );
While ($ Result = mysql_fetch_row ($ Result_ID )){
Print "------------------
";
Print "$ Result [0]
";
Print "$ Result [1]
";
Print "$ Result [2]
";
Print "$ Result [3]
";
Print "-------------------
";
}?>

The basic steps include establishing a connection to the MySQL database, selecting the database operation object, and then executing the query statement. In general, the prompts for errors in the above process can be described in a more accurate and detailed manner. For example, the "Connection failed due to a bad username" error report clearly indicates that the Connection to the database fails due to a user name error.

We can use the return values of these functions mentioned above to reduce unnecessary troubles. For example, the mysql_connect function returns a Connection ID when the connection is successful. if the connection fails, an error is returned. In this regard, we can make the following use:

If (! Mysql_connect ('localhost', 'root', 'password ')){
Print "Cannot connect to MySQL
";
Exit;
}

When there is a problem with the database connection, we can output an error prompt and terminate the program execution. In the long run, this is a very good precaution. In this way, we re-compile the script as follows:

   $ Host = "localhost ";
$ MySQL_UserName = "root ";
$ MySQL_UserPass = "password ";
$ MySQL_Database = "db ";
$ Query = "SELECT * FROM domain ";
If (! Mysql_connect ($ Host, $ MySQL_UserName, $ MySQL_UserPass )){
Print "Cannot connect to MySQL:". mysql_error ();
Exit;
}
If (! Mysql_select_db ($ MySQL_Database )){
Print "Cannot select db
";
Exit;
}
If (! $ Result_ID = mysql_query ($ Query )){
Print "Query Error:". mysql_error ();
Exit;
}
While ($ Result = mysql_fetch_row ($ Result_ID )){
Print "------------------
";
Print "$ Result [0]
";
Print "$ Result [1]
";
Print "$ Result [2]
";
Print "$ Result [3]
";
Print "-------------------
";
}
?>


In this way, when a program encounters a problem, we can immediately find the root cause of the error, so as to be targeted.


Next, we can query the database. However, many times, when we run the compiled query statement, we do not get any returned data. What is an error? The best solution is to assign the SQL statement to a variable, for example:

   ....
$ SQL = "SELECT * FROM $ TableName WHERE $ ColumnName> $ Limit ";
$ Result_ID = mysql_query ($ QUERY );
...?>


Then, when a problem occurs, run the "print" or "echo" command to display the statement. Check whether the spelling of $ ColumnName and $ Limit is correct and whether new variables are created unintentionally. The output display method can easily locate and solve spelling errors. But what if no obvious error is found after the SQL statement is displayed? Here we can paste the output statement into a command line tool like the Mysql command line interface to see if data can be returned. If the problem persists, check the account's user permissions.

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.