试试这个...它消除了对 mysql_select_db() 函数的错误抑制,并在您的 Web 浏览器中强制显示错误。
第一次修订
<?php
error_reporting(E_ALL); // Report on all errors
ini_set('display_errors', '1'); // Display those errors through the web page.
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Tables from MySQL Database</title>
<style type="text/css">
table.db-table { border-right:1px solid #ccc; border-bottom:1px solid #ccc; }
table.db-table th { background:#eee; padding:5px; border-left:1px solid #ccc; border-top:1px solid #ccc; }
table.db-table td { padding:5px; border-left:1px solid #ccc; border-top:1px solid #ccc; }
</style>
</head>
<body>
<table>
<?php
/* connect to the db */
$connection = mysql_connect('localhost','user','password');
mysql_select_db('test',$connection);
if (!mysql_select_db('test',$connection)) {
exit('<p>Unable to locate the test ' .
'database at this time.</p>');
}
$result = mysql_query("SELECT Annual_Sales, Name,address,phone FROM exampleco");
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
?>
<tr>
<td><?=$row['Annual_Sales']; ?></td>
<td><?=$row['name']; ?></td>
<td><?=$row['address']; ?></td>
<td><?=$row['phone']; ?></td>
</tr>
<?php
}
mysql_free_result($result);
?>
</table>
</body>
</html>
每当您使用 PHP 编程并且该代码尚未准备好投入生产时,我强烈建议您确保显示错误。PHP 错误通常非常有用,可以极大地帮助开发过程!
修订版 2
包括更多打印以帮助追踪问题。
<?php
print 'Started.<br />';
error_reporting(E_ALL); // Report on all errors
ini_set('display_errors', '1'); // Display those errors through the web page.
print 'Errors Now Showing. To test, the following line should display an error:<br />';
print $a_var_which_doesnt_exist;
print '<br />';
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Tables from MySQL Database</title>
<style type="text/css">
table.db-table { border-right:1px solid #ccc; border-bottom:1px solid #ccc; }
table.db-table th { background:#eee; padding:5px; border-left:1px solid #ccc; border-top:1px solid #ccc; }
table.db-table td { padding:5px; border-left:1px solid #ccc; border-top:1px solid #ccc; }
</style>
</head>
<body>
<table>
<?php
/* connect to the db */
$connection = mysql_connect('localhost', 'user', 'password');
if(!$connection) { // Ensure connection successful.
die('<p>Could not connect: ' . mysql_error() . '</p>');
}
$db_sel = mysql_select_db('test', $connection);
if($db_sel) { // Ensure we're able to select database.
die('<p>Could not select DB: ' . mysql_error() . '</p>');
}
$result = mysql_query('SELECT Annual_Sales, Name,address,phone FROM exampleco') or die('<p>Error with the query: ' . mysql_error() . '</p>');
if(mysql_num_rows($result)) {
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
?>
<tr>
<td><?=$row['Annual_Sales']; ?></td>
<td><?=$row['name']; ?></td>
<td><?=$row['address']; ?></td>
<td><?=$row['phone']; ?></td>
</tr>
<?php
}
} else {
?>
<tr><td colspan="4">NO ROWS RETURNED BY QUERY</td></tr>
<?php
}
mysql_free_result($result);
?>
</table>
</body>
</html>
<?php print 'Finished.<br />';