时间:2021-07-01 10:21:17 帮助过:14人阅读
在网页中显示数据库里面的内容:
//首先在页面内添加一个表格,并设置列名 <table class="table table-bordered"> <thead> <tr> <th>id</th> <th>title</th> <th>author</th> <th>source</th> <th>date</th> <th>update</th> <th>delete</th> </tr> </thead> //表身内容为数据库存储的内容,对其进行展示 <tbody> <?php $db = new MySQLi("localhost","root","123","newssystem"); $sql = "select * from news"; $result = $db->query($sql); if($result){ $arr = $result->fetch_all(); foreach($arr as $v){ echo "<tr> <td>{$v[0]}</td> <td>{$v[1]}</td> <td>{$v[2]}</td> <td>{$v[3]}</td> <td>{$v[5]}</td> <td> <a href=‘xiugai.php?newsid={$v[0]}‘ ><button type=‘button‘ class=‘btn btn-primary btn-sm‘>修改</button></a> </td> <td> <a href=‘shanchu.php?title={$v[1]}‘ onclick=\"return confirm(‘确认删除么?‘)\">
<button type=‘button‘ class=‘btn btn-primary btn-sm‘>删除</button>
</a> </td> </tr>"; } } ?> </tbody> </table>
对数据进行删除:
<?php $title = $_GET["title"]; $db = new MySQLi("localhost","root","123","newssystem"); $sql = "delete from news where title=‘{$title}‘"; $result = $db->query($sql); if($result){ header("location:chakan.php"); }else{ echo "删除失败!"; }
如果实现批量删除:
首先在列表每一行最前面加上一个复选框:
<td><input type=‘checkbox‘ class=‘ck‘ name=‘ck[]‘ value=‘{$v[0]}‘/>{$v[0]}</td>
然后在列表列的最前面加入一个可以全选的复选框:
<input type="checkbox" id="ckall" />
加入JS代码实现全选:
<script type="text/javascript"> var ckall = document.getElementById("ckall"); ckall.onclick = function(){ var xz = ckall.checked; var ck = document.getElementsByClassName("ck"); for(var i=0;i<ck.length;i++){ ck[i].checked = xz; } } </script>
加入批量删除按钮,然后使其可以运行下一个页面的代码:
<?php $arr = $_POST["ck"]; //delete from info where code in(‘p001‘,‘p002‘,‘p003‘) $str = implode("‘,‘",$arr); $sql = "delete from info where code in(‘{$str}‘)"; $db = new MySQLi("localhost","root","123","mydb"); $result = $db->query($sql); if($result){ header("location:main.php"); }else{ echo "删除失败!"; }
即可实现批量删除功能。
对数据修改(需要同时运用到添加和删除):
首先先将要修改的数据展示出来:
//在要展示的修改的页面加入一段php代码 <?php //取出主键值 $newsid = $_GET["newsid"]; //读取该条数据 $db = new MySQLi("localhost","root","123","newssystem"); $sql = "select * from news where newsid={$newsid}"; $result = $db->query($sql); $arr1 = $result->fetch_row(); ?>
然后在每一条数据内使其内容显示出来(给文本框赋值),如:<?php echo $arr1[0] ?>
在新建一个只有php的页面:
<?php $newsid = $_POST["newsid"]; $title = $_POST["title"]; $Author = $_POST["Author"]; $source = $_POST["source"]; $content = $_POST["content"]; $db = new MySQLi("localhost","root","123","newssystem"); $sql = "update news set title=‘{$title}‘,Author=‘{$Author}‘,source=‘{$source}‘,content=‘{$content}‘ where newsid = {$newsid}"; $result = $db->query($sql); if($result){ header("location:chakan.php"); }else{ echo "修改失败!"; }
php页面中实现对数据库的操作
标签:fetch nts str sid 库存 header 全选 java var