PHP使用MySQL数据库,从建立连接到结果的显示。
完整代码如下:
<? php // 连接MySQL $db = mysql_connect ("localhost","root","root" ); if (! $db ) { die ('Could not connect: ' . mysql_error ()); } // 创建数据库 if (! mysql_query ("CREATE DATABASE my_db", $db )) { echo "Error creating database: " . mysql_error (); } // 选择数据库 mysql_select_db ("my_db", $db ); // 创建表 $sql = " CREATE TABLE Persons ( FirstName varchar(15), LastName varchar(15), Age int ) " ; mysql_query ( $sql , $db ); // 插入数据 mysql_query (" INSERT INTO Persons (FirstName, LastName, Age) VALUES ('Peter', 'Griffin', '35') " ); mysql_query (" INSERT INTO Persons (FirstName, LastName, Age) VALUES ('Glenn', 'Quagmire', '33') " ); // 创建结果集 $sql = "SELECT * FROM Persons" ; $result = mysql_query ( $sql ); // 在 HTML 表格中显示结果 echo " <table border='1'> <tr> <th>FirstName</th> <th>LastName</th> <th>Age</th> </tr> " ; while ( $rs = mysql_fetch_array ( $result )) { echo "<tr>" ; echo "<td>" . $rs ['FirstName'] . "</td>" ; echo "<td>" . $rs ['LastName'] . "</td>" ; echo "<td>" . $rs ['Age'] . "</td>" ; echo "</tr>" ; } echo "</table>" ; // 关闭连接 mysql_close ( $db ); ?>
注:创建数据库及建表只在第一次建好即可。
效果如图: