1:user表:
CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(32) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8
2:mysqltools.php (mysql工具类)
<?php class MySqlTools{ private $host='127.0.0.1'; private $uname='root'; private $pwd='mysql'; private $dbname='test'; private $conn; function __construct(){ $this->conn=mysql_connect($this->host,$this->uname,$this->pwd) or die('mysql_connect error:'.mysql_error()); mysql_select_db($this->dbname) or die('mysql_select_db error:'.mysql_error()); mysql_query("set names 'utf8'"); } function exec_dql($sql){ $result=mysql_query($sql,$this->conn); $arr=array(); while($row=mysql_fetch_assoc($result)){ $arr[]=$row; } mysql_free_result($result); return $arr; } function exec_dml($sql){ return mysql_query($sql,$this->conn); } function free(){ mysql_close($this->conn); } } ?>
3:index.php (首页)
<html> <head> <title>Index</title> </head> <body> <?php require_once 'mysqltools.php'; $mysql=new MySqlTools(); $sql='select id,name from user'; $users=$mysql->exec_dql($sql); ?> <table style="50%;"> <tr> <th>ID</th> <th>Name</th> <th>Oper</th> </tr> <?php foreach($users as $user){ ?> <tr align="center"> <td><?php echo $user['id'];?></td> <td><?php echo $user['name'];?></td> <td> <a href="show.php?id=<?php echo $user['id'];?>">详情</a> <a href="delete.php?id=<?php echo $user['id'];?>">删除</a> </td> </tr> <?php }?> </table> <hr/> <h2><a href="add.php">Add a new user</a></h2> </body> </html>
4:add.php (增加新用户)
<html> <head> <title>Add</title> <meta http-equiv="content-type" content="text/html;charset=utf-8"/> </head> <body> <h1>Add</h1><a href="index.php">Index</a><br/> <?php if(!empty($_POST['uname'])){ $name=$_POST['uname']; require_once 'mysqltools.php'; $sql="insert into user(name) values('$name')"; $mysql=new MySqlTools(); if($mysql->exec_dml($sql)){ echo '<h3>Add Success!</h3>'; }else{ echo '<h3>Add Error!</h3>'; } } ?> <form method="post"> Name:<input type="text" name="uname"/> <input type="submit" value="Add"/> </form> </body> </html>
5:delete.php (删除操作)
<?php $id=$_GET['id']; if(isset($id)){ require_once 'mysqltools.php'; $mysql=new MySqlTools(); $sql="delete from user where id=$id"; $mysql->exec_dml($sql); } header('Location: index.php'); ?>
6:show.php (显示详细信息页面)
<?php header('Conent-Type:text/html;charset=utf-8'); $id=$_GET['id']; $name=''; if(isset($id)){ require_once 'mysqltools.php'; $mysql=new MySqlTools(); $sql="select name from user where id=$id limit 1"; $arr=$mysql->exec_dql($sql); $name=$arr[0]['name']; } echo "ID:$id<br/>Name:$name<br/>"; echo '<h3><a href="index.php">Index</a></h3>'; ?>