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.