1、 在创建表、对表进行操作之前,必须首先选择数据库。通过 mysql_select_db() 函数选取数据库。 当您创建 varchar 类型的数据库字段时,必须规定该字段的最大长度,例如:varchar(15)。
1 <? php 2 $con = mysql_connect ("localhost","peter","abc123" ); 3 if (! $con ) 4 { 5 die ('Could not connect: ' . mysql_error ()); 6 } 7 8 // Create database 9 if ( mysql_query ("CREATE DATABASE my_db", $con )) 10 { 11 echo "Database created" ; 12 } 13 else 14 { 15 echo "Error creating database: " . mysql_error (); 16 } 17 18 // Create table in my_db database 19 mysql_select_db ("my_db", $con ); 20 $sql = " CREATE TABLE Persons 21 ( 22 FirstName varchar(15), 23 LastName varchar(15), 24 Age int 25 )" ; 26 mysql_query ( $sql , $con ); 27 28 mysql_close ( $con ); 29 ?>
2、 mysql_fetch_array() 函数以数组的形式从记录集返回第一行。每个随后对 mysql_fetch_array() 函数的调用都会返回记录集中的下一行。
<? php $con = mysql_connect ("localhost","peter","abc123" ); if (! $con ) { die ('Could not connect: ' . mysql_error ()); } mysql_select_db ("my_db", $con ); $result = mysql_query ("SELECT * FROM Persons" ); while ( $row = mysql_fetch_array ( $result )) { echo $row ['FirstName'] . " " . $row ['LastName' ]; echo "<br />" ; } mysql_close ( $con ); ?>
将查询结果显示在表格中。
<? php $con = mysql_connect ("localhost","peter","abc123" ); if (! $con ) { die ('Could not connect: ' . mysql_error ()); } mysql_select_db ("my_db", $con ); $result = mysql_query ("SELECT * FROM Persons" ); echo " <table border='1'> <tr> <th>Firstname</th> <th>Lastname</th> </tr> " ; while ( $row = mysql_fetch_array ( $result )) { echo "<tr>" ; echo "<td>" . $row ['FirstName'] . "</td>" ; echo "<td>" . $row ['LastName'] . "</td>" ; echo "</tr>" ; } echo "</table>" ; mysql_close ( $con ); ?>
3、