调出mysql中数据,输出一个二维数组的表格

  • A+
所属分类:PHP技术

1、使用DDL语句创建数据库、创建表。

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| class_info         |
| houdunwang         |
| mysql              |
| test               |
+--------------------+
5 rows in set (0.00 sec)

mysql> create database student_info;
Query OK, 1 row affected (0.01 sec)

mysql>   CREATE TABLE student_info(
   ->   id int(6) not null primary key,
   ->   name varchar(20),
   ->   sex char(4),
   ->   age tinyint(3)
   -> );
Query OK, 0 rows affected (0.06 sec)

2、向student_info 表中插入数据:

insert into student_info values("000004","david.sun","nv","26");

3、查看当前student_info表内的数据:

mysql> select * from student_info;
+----+-------------+------+------+
| id | name        | sex  | age  |
+----+-------------+------+------+
 1 | david.zhang | man  |   51 |
 2 | david.liu   | nv   |   26 |
 3 | david.li    | man  |   26 |
 4 | david.sun   | nv   |   26 |
+----+-------------+------+------+
4 rows in set (0.00 sec)

4、编写php程序

//连接数据库

mysql_connect("localhost","root","123456",);

//选择数据库

mysql_select_db("student_info");

//查询student_info表内的数据

$output=mysql_query("select * from student_info");  //查询出来的数据类型为资源类型。

//将student_info表数据输出一条

//mysql_fetch_assoc($output);  //数据的数据类型为一维数组,只有一条数据。如果想输出多条数据,需要使用循环来实现。

while($arr=mysql_fetch_assoc($output)){

           $arr_one[]=$arr;   // 使用while循环,遍历出mysql数据表中的每一条数据。遍历出来的是一个二位数组。如下是,将所有的数据以表格的形式输出。

}

?>

<table width=300 border=1 align="center">

<caption><h2>学生信息表</h2></caption> 

     <tr>

          <td>id</td>

          <td>name</td>

          <td>sex</td>

          <td>age</td>

     </tr>

<?php

  foreach($arr_one as $key=>$val){

?>

          <tr>

             <td><?php echo $val[id]?></td>

             <td><?php echo $val[name]?></td>

             <td><?php echo $val[sex]?></td>

             <td><?php echo $val[age]?></td>

          </tr>

<?php

}

?>

</table>

发表评论

您必须登录才能发表评论!