PHP CRUD

<body>
<table class="table table-striped">
  <caption>新闻表</caption>
  <thead>
    <tr>
      <th>id</th>
      <th>title</th>
      <th>author</th>
      <th>source</th>
      <th>date</th>
      <th>操作</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='./delete.php?id={$v[0]}' onclick=\"return confirm('确认删除么?')\"><button type='button' class='btn btn-default btn-sm'>删除</button></a>
      //传一个参数到执行页面
<a href='./xiugai.php?id={
$v[0]}' ><button type='button' class='btn btn-default btn-sm'>修改</button></a> //传一个参数到修改页面
</td> </tr>
"; } } ?> </tbody> </table> <div><a href="./tianjia.php">添加数据</a></div>//跳转到添加数据页面 </body>

删除动作:

<?php
$id = $_GET["id"];//获取传过来的id值
$db = new MySQLi("localhost","root","123","newssystem");
$sql = "delete from news where newsid={$id}";//newsid数据类型为整数,不加单引号
$result = $db->query($sql);


if($result){
    header("location:main.php");//执行成功,跳转页面,注意加双引号。
    }else{
        echo "删除失败";
        }

添加数据页面:

<form action="./add.php" method="post">//执行提交表单的页面,方法为post
<div class="panel panel-default" style="max-width:500px">
    <div class="panel-body">
     <div class="input-group">
            <span class="input-group-addon">标题:</span>
            <input type="text" class="form-control" placeholder="请输入新闻标题" name="title">
        </div>
        
      <br />
         <div class="input-group">
            <span class="input-group-addon">作者:</span>
            <input type="text" class="form-control" placeholder="请输入作者"name="author">
        </div>
        
        <br />
         <div class="input-group">
            <span class="input-group-addon">来源:</span>
            <input type="text" class="form-control" placeholder="请输入来源"name="source">
        </div>
       <br />
         <div class="input-group">
            <span class="input-group-addon">内容:</span>
            <input type="text" class="form-control" placeholder="请输入内容"name="content">
        </div>
        <br/>
        <input class="btn btn-default" type="submit" value="提交">
        <a href="main.php">查看</a> //跳转到主页面
       
    </div>
    </div>
</form>

执行添加数据操作页面

$title = $_POST["title"];//获取post方法传过来的数据
$author = $_POST["author"];
$source = $_POST["source"];
$content = $_POST["content"];

$db = new MySQLi("localhost","root","123","newssystem");
$sql = "insert into news  values(0,'{$title}','{$author}','{$source}','{$content}',now())";
$result = $db->query($sql);


if($result){
    header("location:tianjia.php");
    
    }else{
        echo "添加失败!";
        }

 

posted @ 2018-01-16 13:50  niushuangmeng  阅读(153)  评论(0编辑  收藏  举报