Tip: Php+mysql Dynamic Web page Programming error correction guide

Source: Internet
Author: User
Tags exit execution connect mysql variables parse error variable scope mysql database

As for the database in the Web programming, the function of the database is more and more cannot be neglected. Referring to the database, it should be said that PHP has very strong database support capabilities, from FileMaker to Oracle, almost all of the database system can be seamless connectivity. In order to facilitate the explanation of this article, we will mainly take MySQL as an example to explain. But it's also true for 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------------------<BR>;
Print "$Result [0]<br>";
Print "$Result [1]<br>";
Print "$Result [2]<br>";
Print "$Result [3]<br>";
Print-------------------<BR>;
}?>

The basic steps include establishing a connection to the MySQL database, selecting the database Operation object, and then executing the query statement. In general, information about the errors that occur in the above process can be described in a more accurate and detailed description of the problems that arise. For example, the "Connection failed due to a bad username" error report clearly indicates that the connection to the database failed due to a user name error.

We can take advantage of the return values of these functions mentioned above, thus reducing unnecessary trouble. For example, the Mysql_connect function returns a connection ID identity when the connection succeeds, and an error message if the connection fails. In this respect, we can use the following:

if (!mysql_connect (' localhost ', ' root ', ' password ')) {
Print "Cannot connect to mysql<br>";
Exit
}

When there is a problem with the connection to the database, we can output the error prompt and terminate the execution of the program. In the long run, this is a very good precaution. In this way, we rewrite 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<br>";
Exit
}
if (! $Result _id=mysql_query ($Query)) {
Print "Query Error:". Mysql_error ();
Exit
}
while ($Result =mysql_fetch_row ($Result _id)) {
Print------------------<BR>;
Print "$Result [0]<br>";
Print "$Result [1]<br>";
Print "$Result [2]<br>";
Print "$Result [3]<br>";
Print-------------------<BR>;
}?>

In this way, when there is a problem with the program, we can immediately find the root cause of the error, so that can be targeted.

Next, we can query the database. However, most of the time, when we run a written query, we don't get any return data. Where did it go wrong? The best solution is to give the SQL statement a variable, such as:

?
....
$SQL = "SELECT * from $TableName WHERE $ColumnName > $Limit";
$Result _id=mysql_query ($QUERY);
...? >

Then, when a problem occurs, use the print or ECHO command to display the statement. Note Check that the spelling of $columnname and $limit is correct, and whether new variables are created unintentionally. Using the output display method makes it easy to find and troubleshoot spelling errors. But what if we still haven't found the obvious error 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 we can return the data. If you still cannot resolve the problem, you should review the user rights for the account you are using.

Today, we can use a number of free classes to complete most of the database operations. PHP Classes (http://phpclasses.upperdesign.com/) has a lot of relevant information, for interested users to refer to. In this case, metabase can provide queries and management that do not rely on a database system. If users are using several different database systems at the same time, or want their programs to be ported to other database platforms, be aware of the use of metabase.

Note In the end, we use PHP programming process should pay attention to some of the issues to be summed up, hoping to be helpful to everyone.

1. Check (), [], and {} symbols to see if they appear in pairs.
2. Check the string, and note that if you want to use the "" in "", you must use the escape character "\".
3. Check that the reserved keyword is spelled correctly. For example, Myslq_num_rows () should be changed to mysql_num_rows.
4. Check the syntax of the program against the PHP user manual (Www.php.net/manual).
5. If you use global variables in a function, be sure not to forget to make a variable declaration.
6. If you want to use the Setcookie () function to set cookie information, be sure to not print any characters before this, including the or "<?php" cannot have any spaces before it. "A;?" Must be the first line of the program.
7. If the database query operation fails, write out the query using Echo or print, check that the syntax is correct, and pay special attention to the variables that appear in the statement.
8. If there is no obvious problem with the SQL statement, you can try to use the command-line interface provided by the database system.
9. If the problem remains unresolved, you should check to see if you have sufficient database access rights.
10. If the "can" T redeclare foo () error appears, the user may have referenced the same file two times. You can use the include_once () function to avoid this problem.
11. Note that case sensitivity is case-sensitive. For example, $Foo and $foo are two different variables.
12. Note the correct use format for 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 like when we write an article we have to add a period at the end of every sentence, PHP requires that every statement in the program must use a semicolon ";" This is the most basic grammatical rule, but it is also the most prone to problems. When we write a program, we rarely check whether the semicolon is missing on one line, but once any negligence occurs, the parser sends out an error report immediately. In some cases, the report may contain the number of statement lines in which the problem occurs.

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

At the end of the second line of the code, "Echo $Output," We missed a semicolon, and if you execute the script you will get the following error message:

Parse error:parse error, expecting ', ', ' or '; ' in/usr/local/apache/htdocs/test.php on line 8 the report, while pointing out the cause of the error, omitted the comma "," or Semicolon ";", but the problem statement is set to line eighth. Because this code is very simple, it's easy to find where the error really occurs. However, if the program is very complex, it may be difficult to find a smooth error.

According to the author's previous experience, the following methods are recommended:

If the statement that is indicated in the error report does not have an obvious problem, you can check that the other instruction lines (excluding the comment lines) before the statement are correct. If you still do not find the error, you can comment out the statement line that is indicated in the report (precede the line with the "//" or "#" annotation symbol) or change to another statement where the user can ensure that there is no problem at all. After that, rerun the program, and if the error message still points to the same line, it indicates that the statement that really has the problem should be in front of the statement line that was commented out. Follow the above method to check each line of command before the position, until the error message changes. At this time, we have successfully dug out the real culprit.

The question of variables differs from other programming languages requiring users to explicitly declare variables, and the PHP language allows users to automatically use all variables without having to make a prior declaration. The spelling error of variable names is a big problem for PHP users.

?
function Combine ($FirstHalf, $SecondHalf)
{
$Combined _string= $FirstHalf. $SecondHalf;
return $Combined _string;
}
$FirstString = "WDVL-";
$SecondString = "Illustrated Encyclopedia";
$Combine _result=combine ($FirstString, $SecondString);
Print $Combined _result;
?>

When we run the above script, we will see the error prompts that occur because the program does not return any data. Here, we have chosen a very intuitive example for a better explanation of the problem. In reality, sometimes the problem is not so simple. I believe everyone has found the cause of the problem, that is, "Print $Combined _result;" The variable name "$Combined _result" in should be changed to "$Combine _result."
In fact, any spelling mistakes that occur in a script can cause the same problem. If the user suspects that there is a spelling error in their program, a very good way to check is to display text information before and after the variable. For example:

Print "The Combined result is: |". $Combined _result. "|";

The results of the script that replaces the output statement with the above method are as follows:

The Combined result is: | |

Where, in two pipe symbols "|" No content between. In this way, we can find the variable in the program where the problem occurs.

Next, let's take a more complicated example to illustrate.

Now, many network applications need to authenticate the identity of the user. One of the simplest implementation scripts can be 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";
}
?>

While calling the VerifyPassword function in the script above, the wrong password was entered, but after the program is run, the following results are still produced:

The Password is correct

The problem may be anywhere, let's use the elimination method to check. First, it is difficult to determine whether the final "if" conditional statement of the script is correct. It seems to be no problem, but to ensure that the program is correct, we can not let go of any link. Therefore, we annotate the conditional statement and output the VerifyPassword () function according to the method described earlier. Specifically 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 used the wrong password, the result should be 0. But after the program runs, we find that the actual results are as follows:

The result of VerifyPassword () is:1

In this way, we know that the problem is appearing on the VerifyPassword () function. After examining the function, we suspect that the problem may appear in an "if" statement. So we mask the conditional statements in the VerifyPassword () function and do the following output:

Print "UserPassword => $UserPassword, Password => $Password,";
Print "Password==userpassword =>". (int) ($Password = = $UserPassword). " <BR> ";
Print "UserName => $UserName, Name => $Name,";
Print "Name==username =>". (int) ($Name = = $UserName). " <BR> ";

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

The actual output 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 password and name two variables are null values, it is no wonder that the judgment statement does not work.

So why is $password a null value? We have explicitly assigned the $password variable at the beginning of the program, but because some of its variable values cannot be brought into the VerifyPassword () function. Recall the PHP language about variable scope rules, we can immediately find the cause of the problem, that is, if you want to use the variable in the function, you must declare the variable as a global variable. Once we know the source of the error, we add the following statement to the first line of the VerifyPassword () function, and then rerun the program:

Global $Password, $Name;

The results of the program operation are as follows:

UserPassword => foo1ish, Password => Secret, Password==userpassword => 0
UserName => Admin, Name => Admin, name==username => 1
The Password is correct

Why? Logically, we should get the wrong hint of incorrect password. After a careful examination of the program, finally found that we have the logical operator "= =" misuse into "=", so that the value of the $userpassword variable assigned to the $password variable. After correcting the last two errors, the following procedures are completed:

?
$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 implementation procedure has the following results:

I ' m Sorry, the password is incorrect.

When you enter the correct password to rerun, the following results are obtained:

The Password is correct

In this way, we succeeded in finding and solving the problem. I hope you can learn from the above introduction to find some of the wrong way and ideas.

As for the database in the Web programming, the function of the database is more and more cannot be neglected. Referring to the database, it should be said that PHP has very strong database support capabilities, from FileMaker to Oracle, almost all of the database system can be seamless connectivity. In order to facilitate the explanation of this article, we will mainly take MySQL as an example to explain. But it's also true for 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 "------------------<BR>";
Print "$Result [0]<br>";
Print "$Result [1]<br>";
Print "$Result [2]<br>";
Print "$Result [3]<br>";
Print "-------------------<BR>";
}?>

The basic steps include establishing a connection to the MySQL database, selecting the database Operation object, and then executing the query statement. In general, information about the errors that occur in the above process can be described in a more accurate and detailed description of the problems that arise. For example, the "Connection failed due to a bad username" error report clearly indicates that the connection to the database failed due to a user name error.

We can take advantage of the return values of these functions mentioned above, thus reducing unnecessary trouble. For example, the Mysql_connect function returns a connection ID identity when the connection succeeds, and an error message if the connection fails. In this respect, we can use the following:

if (!mysql_connect (' localhost ', ' root ', ' password ')) {
Print "Cannot connect to mysql<br>";
Exit
}

When there is a problem with the connection to the database, we can output the error prompt and terminate the execution of the program. In the long run, this is a very good precaution. In this way, we rewrite 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<br>";
Exit
}
if (! $Result _id=mysql_query ($Query)) {
Print "Query Error:". Mysql_error ();
Exit
}
while ($Result =mysql_fetch_row ($Result _id)) {
Print "------------------<BR>";
Print "$Result [0]<br>";
Print "$Result [1]<br>";
Print "$Result [2]<br>";
Print "$Result [3]<br>";
Print "-------------------<BR>";
}?>

In this way, when there is a problem with the program, we can immediately find the root cause of the error, so that can be targeted.

Next, we can query the database. However, most of the time, when we run a written query, we don't get any return data. Where did it go wrong? The best solution is to give the SQL statement a variable, such as:

?
....
$SQL = "SELECT * from $TableName WHERE $ColumnName > $Limit";
$Result _id=mysql_query ($QUERY);
...? >

Then, when a problem occurs, use the print or ECHO command to display the statement. Note Check that the spelling of $columnname and $limit is correct, and whether new variables are created unintentionally. Using the output display method makes it easy to find and troubleshoot spelling errors. But what if we still haven't found the obvious error 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 we can return the data. If you still cannot resolve the problem, you should review the user rights for the account you are using.



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.