w3pop.com :: 网络学院 :: PHP :: MySQL 选择记录
The SELECT statement is used to select data from a database.
选择语句[SELECT]是用来从一个数据库中选取数据的。
The SELECT statement is used to select data from a database.
选择语句[SELECT] 是用来从一个数据库中选取数据的。
SELECT column_name(s) FROM table_name |
Note: SQL statements are not case sensitive. SELECT is the same as select.
注意:SQL语句是“字母大小写不敏感”的语句(它不区分字母的大小写),即:“SELECT”和“select”是一样的。
To get PHP to execute the statement above we must use the mysql_query() function. This function is used to send a query or command to a MySQL connection.
在PHP内创建数据库,我们需要在mysql_query()函数内使用上述语句。这个函数是用来发送MySQL数据库连接建立的请求和指令的。
The following example selects all the data stored in the "Person" table (The * character selects all of the data in the table):
下面这个案例展示了如何从“Person”表中选择所有的数据(通配符“*”表示在表单中选择所有的数据):
<?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 person");
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br />";
}
mysql_close($con); ?> |
The example above stores the data returned by the mysql_query() function in the $result variable. Next, we use the mysql_fetch_array() function to return the first row from the recordset as an array. Each subsequent call to mysql_fetch_array() returns the next row in the recordset. The while loop loops through all the records in the recordset. To print the value of each row, we use the PHP $row variable ($row['FirstName'] and $row['LastName']).
上述案例储存了通过“$result”变量中的“mysql_query()”函数所返回的数据。接下来,我们使用“mysql_fetch_array()”函数将记录中的第一行记录以一个数组的形式返回;那么接下来,如果继续请求“mysql_fetch_array()”函数,那它将返回记录中的第二行,“while loop”语句循环显示了所有的记录。我们使用PHP “$row”变量($row['FirstName'] 和 $row['LastName'])来输出每一行得值。
The output of the code above will be:
上述代码的输出结果如下:
Peter Griffin Glenn Quagmire |
The following example selects the same data as the example above, but will display the data in an HTML table:
下面这个案例:选择了与上述案例相同的数据,并在HTML表格中显示这些数据:
<?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 person");
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); ?> |
The output of the code above will be:
上述代码的输出结果如下:
| Firstname | Lastname |
|---|---|
| Glenn | Quagmire |
| Peter | Griffin |
评论 (0)
All