PHP+MySQL教程(5):MySQL Select_MySQL
Jun 01, 2016 pm 01:57 PMSELECT 语句用于从数据库中选取数据。
从数据库表中选取数据
SELECT 语句用于从数据库中选取数据。
语法
SELECT column_name(s) FROM table_name注释:SQL 语句对大小写不敏感。SELECT 与 select 等效。
为了让 PHP 执行上面的语句,我们必须使用 mysql_query() 函数。该函数用于向 MySQL 发送查询或命令。
例子
下面的例子选取存储在 "Person" 表中的所有数据(* 字符选取表中所有数据):
$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 "
";
}
mysql_close($con);
?>上面这个例子在 $result 变量中存放由 mysql_query() 函数返回的数据。接下来,我们使用 mysql_fetch_array() 函数以数组的形式从记录集返回第一行。每个随后对 mysql_fetch_array() 函数的调用都会返回记录集中的下一行。 while loop 语句会循环记录集中的所有记录。为了输出每行的值,我们使用了 PHP 的 $row 变量 ($row['FirstName'] 和 $row['LastName'])。
以上代码的输出:
Peter Griffin
Glenn Quagmire在 HTML 表格中显示结果
下面的例子选取的数据与上面的例子相同,但是将把数据显示在一个 HTML 表格中:
$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 "
Firstname | Lastname |
---|---|
" . $row['FirstName'] . " | ";" . $row['LastName'] . " | ";
mysql_close($con);
?>以上代码的输出:
Firstname Lastname
Glenn Quagmire
Peter Griffin

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to distinguish database views and tables

How to create and manage database tables using PHP

What are the differences between database views and tables?

What are the differences between database views and tables?

Optimize MySQL table structure to solve connection problems

Data export: customized database table

PHP and PDO: How to perform modification and renaming of database tables

What is the relationship between tables and databases
