pdo.php
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>pdo</title> 6 </head> 7 <body> 8 <p>用户表</p> 9 <table width="1000px" border="1px" cellspacing="0"> 10 <tr> 11 <th>id</th> 12 <th>用户名</th> 13 <th>密码</th> 14 <th>删除</th> 15 </tr> 16 <?php 17 $pdo = new PDO('mysql:host=localhost;dbname=test','root','jia6181813'); 18 $sql = "SELECT * FROM user"; 19 $obj = $pdo->query($sql); 20 //fetch和fetchAll不能同时使用,第一个会覆盖第二个 21 $results = $obj->fetchAll(2); 22 // echo "<pre>"; 23 // print_r($results); 24 // echo "</pre>"; 25 //fetch用while 26 /*while ($row = $obj->fetch()) { 27 echo "<tr>"; 28 echo "<td>$row[id]</td>"; 29 echo "<td>$row[name]</td>"; 30 echo "<td>$row[password]</td>"; 31 echo "</tr>"; 32 }*/ 33 //fetchAll用foreach 34 foreach ($results as $row) { 35 echo "<tr id=$row[id]>"; 36 echo "<td>$row[id]</td>"; 37 echo "<td>$row[name]</td>"; 38 echo "<td>$row[password]</td>"; 39 // echo "<td><a href='delete.php?id={$row[id]}'>删除</a></td>"; 40 echo "<td><a href='javascript:' class='del' num={$row[id]}>删除</a></td>"; 41 echo "</tr>"; 42 } 43 44 ?> 45 </table> 46 47 </body> 48 <script> 49 var objs = document.getElementsByClassName('del'); 50 for (var i = 0; i < objs.length; i++) { 51 objs[i].onclick = function(){ 52 var id = this.getAttribute('num'); 53 //生成ajax对象 54 var xhr = new XMLHttpRequest(); 55 //js get轻轨delete.php文件,同时给该文件传递一个id值,方便删除数据 56 xhr.open("get","delete.php?id="+id,true); 57 //ajax开始异步连接并请求delete.php?id=1 58 xhr.send(); 59 //js监听整个通讯过程 60 xhr.onreadystatechange = function(){ 61 if (xhr.readyState==4) { 62 //responseText能接收php echo的数据 63 r = xhr.responseText; 64 // alert(r); 65 if (r=='1') { 66 //获取tr一行的id 67 var tr = document.getElementById(id); 68 //将这一行隐藏 69 tr.style.display = 'none'; 70 } 71 } 72 } 73 } 74 } 75 76 77 </script> 78 </html>
delete.php
1 <?php 2 $id = $_GET['id']; 3 $pdo = new PDO('mysql:host=localhost;dbname=test','root','123'); 4 $sql = "DELETE FROM user WHERE id={$id}"; 5 //echo "$pdo->exec($sql)"; 6 //$obj = $pdo->query($sql); 7 8 // echo "<script>alert('删除成功')</script>"; 9 //echo "<script>location='pdo.php'</script>"; 10 //if括号里面语句会执行,不需要提前query() 11 if ($pdo->query($sql)) { 12 echo 1; 13 }else{ 14 echo 0; 15 } 16 17 ?>