PHP学习笔记(15)PDO数据库操作+AJAX无刷新技术删除用户

时间:2022-03-03 01:01:50

pdo.php

 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>pdo</title>
</head>
<body>
<p>用户表</p>
<table width="1000px" border="1px" cellspacing="0">
<tr>
<th>id</th>
<th>用户名</th>
<th>密码</th>
<th>删除</th>
</tr>
<?php
$pdo = new PDO('mysql:host=localhost;dbname=test','root','jia6181813');
$sql = "SELECT * FROM user";
$obj = $pdo->query($sql);
//fetch和fetchAll不能同时使用,第一个会覆盖第二个
$results = $obj->fetchAll(2);
// echo "<pre>";
// print_r($results);
// echo "</pre>";
//fetch用while
/*while ($row = $obj->fetch()) {
echo "<tr>";
echo "<td>$row[id]</td>";
echo "<td>$row[name]</td>";
echo "<td>$row[password]</td>";
echo "</tr>";
}*/
//fetchAll用foreach
foreach ($results as $row) {
echo "<tr id=$row[id]>";
echo "<td>$row[id]</td>";
echo "<td>$row[name]</td>";
echo "<td>$row[password]</td>";
// echo "<td><a href='delete.php?id={$row[id]}'>删除</a></td>";
echo "<td><a href='javascript:' class='del' num={$row[id]}>删除</a></td>";
echo "</tr>";
} ?>
</table> </body>
<script>
var objs = document.getElementsByClassName('del');
for (var i = 0; i < objs.length; i++) {
objs[i].onclick = function(){
var id = this.getAttribute('num');
//生成ajax对象
var xhr = new XMLHttpRequest();
//js get轻轨delete.php文件,同时给该文件传递一个id值,方便删除数据
xhr.open("get","delete.php?id="+id,true);
//ajax开始异步连接并请求delete.php?id=1
xhr.send();
//js监听整个通讯过程
xhr.onreadystatechange = function(){
if (xhr.readyState==4) {
//responseText能接收php echo的数据
r = xhr.responseText;
// alert(r);
if (r=='1') {
//获取tr一行的id
var tr = document.getElementById(id);
//将这一行隐藏
tr.style.display = 'none';
}
}
}
}
} </script>
</html>

delete.php

 <?php
$id = $_GET['id'];
$pdo = new PDO('mysql:host=localhost;dbname=test','root','123');
$sql = "DELETE FROM user WHERE id={$id}";
//echo "$pdo->exec($sql)";
//$obj = $pdo->query($sql); // echo "<script>alert('删除成功')</script>";
//echo "<script>location='pdo.php'</script>";
//if括号里面语句会执行,不需要提前query()
if ($pdo->query($sql)) {
echo 1;
}else{
echo 0;
} ?>