<body> <h1>主页面</h1> <!--把Info表查出来,用一个表格显示--> <table width="100%" cellpadding="0" cellspacing="0" border="1"> <tr> <td>代号</td> <td>姓名</td> <td>性别</td> <td>民族</td> <td>生日</td> <td>操作</td> </tr> <?php $db=new MySQLi("localhost","root","","mydb"); !mysqli_connect_error() or die ("连接失败"); $sql="select * from Info"; $result=$db->query($sql); $arr=$result->fetch_all(); foreach($arr as $v) { $sex = $v[2]?'男':'女'; //处理民族名称 $sqln = "select Name from Nation where Code='{$v[3]}'"; $r = $db->query($sqln); $attr = $r->fetch_assoc(); echo "<tr> <td>{$v[0]}</td> <td>{$v[1]}</td> <td>{$sex}</td> <td>{$attr['Name']}</td> <td>{$v[4]}</td> <td> <a href='Delete.php?code={$v[0]}'>删除</a> <a href='Update.php?code={$v[0]}'>修改</a>//修改的话需要知道修改哪条数据,主键能唯一确定一条数据,所以需要传主键值给Update.php页面 </td> </tr>"; } ?> </table> <div><a href="Add.php">添加数据</a></div> </body>
图例如上!
下面附上Update.php及UpdateChuLi.php代码
<body> <?php $code=$_GET["code"];//主页里用的GET方法传值到Update.php,所以这里或获取需要用$_GET //var_dump($code); $db=new MySQLi("localhost","root","","mydb"); $sqlcode="select * from Info where code='{$code}'";//通过code查询info表 $result=$db->query($sqlcode); $attrcode=$result->fetch_row(); //个人的所有信息 //var_dump($attrcode); ?> <h1>修改数据</h1> <form action="UpdateChuLi.php" method="post"> <div>代号:<input type="text" name="code"/ value="<?php echo $attrcode[0]?>" readonly="readonly"/></div><br />//修改的话,文本框里需要有之前添加的数据,所以用到value来显示 <div>姓名:<input type="text" name="name" value="<?php echo $attrcode[1] ?>" /></div> <div>性别: <input type="radio" value="男" name="sex" <?php echo $attrcode[2]?"checked='checked'":"" ?>/>男 <input type="radio" value="女" name="sex" <?php echo $attrcode[2]?"":"checked='checked'" ?>/>女 </div><br />//性别返回的值是bool,radio选中属性为checked,可以用条件语句 <div>民族: <select name="nation"> <?php $sql="select * from Nation"; $result=$db->query($sql); $attr=$result->fetch_all(); foreach($attr as $v ) { if($v[0]==$attrcode[3]) { echo "<option select='selected' value='{$v[0]}'>{$v[1]}</option>"; } else { echo "<option value='{$v[0]}'>{$v[1]}</option>"; } } ?> </select></div><br /> <div>生日:<input type="text" name="birthday" value="<?php echo $attrcode[4]?>"/></div><br /> <div><input type="submit" value="修改数据" /></div> <div><a href="main.php">主页</a></div> </form> </body>
<?php $code = $_POST["code"]; $name = $_POST["name"]; $sex = $_POST["sex"]; $s = 1; if($sex == "女") { $s = 0; } $nation = $_POST["nation"]; $birthday = $_POST["birthday"]; $db=new MySQLi("localhost","root","","mydb"); !mysqli_connect_error() or die ("连接失败"); $sql="update Info set Name='{$name}',Sex={$s},Nation='{$nation}',Birthday='{$birthday}' where Code='{$code}' ";//修改的sql语句,利用code来修改 $result=$db->query($sql); if($result) { header("location:main.php");//跳转页面 } else { echo"修改失败"; }