PDO实现学生管理系统(2)

edit.php

<html>
<head>
 <meta charset="UTF-8">
 <title>学生信息管理系统</title>
</head>
<body>
<center>
 <?php include("menu.php");
 //获取修改信息
 //1. 连接数据库
 try{
  $pdo = new PDO("mysql:host=localhost;dbname=myapp;", "root", "");
 
 }catch(PDOException $e){
  die("fail to connect db".$e->getMessage());
 }
 //2. 拼装sql语句,取出信息
 $sql = "SELECT * FROM users WHERE id=".$_GET['id'];
 $stmt = $pdo->query($sql);
 if($stmt->rowCount() > 0){
  $stu = $stmt->fetch(PDO::FETCH_ASSOC); //解析数据
 }else{
  die("没有修改的信息");
 }
 ?>
 <h3>修改学生信息</h3>
 <form action="action.php?action=edit" method="post">
 <!-- 以隐藏域的方式添加id  -->
  <input type="hidden" name="id" value="<?php echo $stu['id']; ?>">
  <table>
   <tr>
    <td>姓名</td>
    <td><input type="text" name="name" value="<?php echo $stu['name'];?>"/></td>
   </tr>
 
   <tr>
    <td>姓别</td>
    <td>
     <input type="radio" name="sex" value="m" <?php echo ($stu['sex']==
      "m")? "checked": ""; ?>/>男
     <input type="radio" name="sex" value="w" <?php echo ($stu['sex']==
      "w")? "checked": ""; ?>/>女
    </td>
 
   </tr>
 
   <tr>
    <td>年龄</td>
    <td><input type="text" name="age" value="<?php echo $stu['age'];?>"/></td>
   </tr>
 
   <tr>
    <td>班级</td>
    <td><input type="text" name="class" value="<?php echo $stu['class'];?>"/></td>
   </tr>
 
   <tr>
    <td> </td>
    <td>
     <input type="submit" value="修改"/>
     <input type="submit" value="重置"/>
    </td>
 
   </tr>
  </table>
 </form>
</center>
</body>
</html>

action.php

<?php
//1. 连接数据库
try{
 $pdo = new PDO("mysql:host=localhost;dbname=myapp;", "root", "");
 
}catch(PDOException $e){
 die("fail to connect db".$e->getMessage());
}
//2. 通过action的值做相应的操作
switch($_GET['action']){
 case "add": //增加操作
  $name = $_POST['name'];
  $sex = $_POST['sex'];
  $age = $_POST['age'];
  $class = $_POST['class'];
 
  $sql = "INSERT INTO users VALUES (null, '{$name}','{$sex}', '{$age}', '{$class}')";
  $rw = $pdo->exec($sql);
  if($rw > 0){
   echo "<script>alert('增加成功'); window.location='index.php'</script>";
  }else{
   echo "<script>alert('增加失败'); window.history.back()</script>";
  }
  break;
 case "del":
  $id = $_GET['id'];
  $sql = "DELETE FROM users WHERE id={$id}";
  $pdo->exec($sql);
  header("location:index.php");
  break;
 case "edit":
  $name = $_POST['name'];
  $sex = $_POST['sex'];
  $age = $_POST['age'];
  $class = $_POST['class'];
  $id = $_POST['id'];
 
  $sql = "UPDATE users SET name='{$name}',sex='{$sex}',age={$age},class={$class}
    WHERE id={$id}";
  $rw = $pdo->exec($sql);
  if($rw > 0){
   echo "<script>alert('修改成功'); window.location='index.php'</script>";
  }else{
   echo "<script>alert('修改失败'); window.history.back()</script>";
  }
  break;
}
      

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/3948.html