一、連接數據庫想要在頁面顯示數據庫表中的內容,並想要隨時刪除不需要的數據,是我們經常要用到的,我們首先新建一個頁面,在Body里面建一個表:
<table width="100%" border="1" cellpadding="0" cellspacing="0"> <tr> <td>代號</td> <td>密碼</td> <td>姓名</td> <td>性別</td> <td>生日</td> <td>操作</td> </tr> </table>
二、然后連接數據庫,循環遍歷出表中的內容,由於表中涉及到性別是bool類型,所以需要轉為男女的格式:
<?php $db = new MySQLi("localhost","root","123","text_0306"); $sql = "select * from users"; $result = $db->query($sql); $arr = $result->fetch_all(); foreach($arr as $v) { //修改性別 $sex = $v[3]?"男":"女"; //修改民族 /*$sql1 = "select name from nation where code='{$v[3]}'"; $r1 = $db->query($sql1); $a1 = $r1->fetch_row();*/ echo "<tr> <td>{$v[0]}</td> <td>{$v[1]}</td> <td>{$v[2]}</td> <td>{$sex}</td> <td>{$v[4]}</td> <td><a href='del.php?uid={$v[0]}' onclick=\"return confirm('確認刪除么?')\">刪除</a></td> </tr>";//這里用到a標簽和點擊事件,點擊事件后面不只可以跟函數,還可以跟js代碼 } ?>
三、上面頁面完成后需要重新建立一個提取數據的頁面,並在刪除成功后跳轉頁面:
<?php $uid = $_GET["uid"];//提取數據 $db = new MySQLi("localhost","root","123","text_0306"); $sql = "delete from users where uid='{$uid}'"; if($db->query($sql)) { //跳轉頁面 header("location:main.php"); /*echo "<script>window.location.href='main.php'</script>";這是第二種跳轉方式,主要用於文件不在同一目錄下時 } else { echo "刪除失敗!"; }
