魏家晗晗

导航

php+mysql

本文整理一下使用php和mysql向前端推送数据的过程。

数据库部分:

1.首先安装服务器,我选择xampp,安装可以选择任意地址。安装完成,打开xampp-control.exe 。

选择开启Apache和MySQL:

2.浏览器进去http://localhost/phpmyadmin/。

这个时候就可以看到数据库页面。新建一个数据库。

3.新建一个数据表,假设我们需要的数据有n个字段,字段数就选择n+1,多出的一个字段用来存放id。

4.新建完成后设置表的内容时,id记得勾选A_I,这样新建的表项id值会自动增加。如果是字符串类型的数据,排序规则选择utf8_general_ci,这样前端也使用utf8编码,不会出现乱码。

5.新建表完成以后,SQL页面可以看到如何使用命令行操作表格,后面我们在代码中对表格的操作也会利用这些命令行。

代码部分:

1.从数据库读取数据并显示在页面上,我们用jquery的ajax读取:

js代码:

var $lists = $("article ul");
    $lists.empty();

    $.ajax({
        url: "server/getnews.php",
        type: "get",/*ajax get方法读取数据*/
        datatype: "json",/*json方式获取*/
        data:{"newstype":newsType},/*传递一个条件,当newstype项的值为newsType时*/
        success: function(data) {
            $.each(data, function(index,item) {/*将data逐条遍历*/
                console.log(item);
                /*将数据内容放置到页面上*/
                var $lists = $("article ul");
                var $list = $("<li></li>").addClass("news-list").prependTo($lists);
                var $newsImg = $("<div></div>").addClass("news-img").appendTo($list);
                console.log(item.newstype);
                var $img = $("<img>").attr("src", item.newsimg).appendTo($newsImg);
                var $newsContent = $("<div></div>").addClass("news-content").appendTo($list);
                var $h1 = $("<h1></h1>").html(item.newstitle).appendTo($newsContent);
                var $p = $("<p></p>").appendTo($newsContent);
                var $newsTime = $("<span></span>").addClass("news-time").html(item.newstime).appendTo($p);
                var $newsSrc = $("<span></span>").addClass("news-src").html(item.newssrc).appendTo($p);
            });

        },
        error: function(){
            console.log('error');
        }
    });

下面看一下getnews.php怎么实现:

<?php
    header("Content-type:application/json;charset=utf-8");
    $link = mysql_connect('localhost','name','pwd');/*连接数据库,后两个参数是数据库的用户名密码*/
    
    if($link){
        mysql_select_db("testabc");/*连接数据库*/
        mysql_query("SET NAMES utf8");
        $newstype=$_GET["newstype"];/*获取参数newstype*/

        if($newstype == "all"){    
            $sql = "SELECT * FROM news";    /*传递命令行,表示获取全部的表项*/                
        }else{            
            $sql = "SELECT * FROM `news` WHERE `newstype` = '{$newstype}'";    /*传递命令行,表示获取所有newstype等于传递的参数的表项*/
        }

        $result = mysql_query($sql,$link);
    
        $senddata = array();

        while($row = mysql_fetch_assoc($result)){
            array_push($senddata,array(
                    'id'=>$row['id'],
                    'newstype'=>$row['newstype'],
                    'newsimg'=>$row['newsimg'],
                    'newstime'=>$row['newstime'],
                    'newssrc'=>$row['newssrc'],
                    'newstitle'=>$row['newstitle']
                ));
        }
        echo json_encode($senddata);        
    }

    mysql_close($link);
    
?>

 

2.向数据库写入数据:

js代码:
//添加一条数据
    $("#btnsubmit").click(function(e) {
        e.preventDefault();
        //提交添加
        var jsonNews = {
            "newstitle": $("#newsTitle").val(),/*从页面读取到的值*/
            "newstype": $("#newsType").val(),
            "newsimg": $("#newsImg").val(),
            "newstime": $("#newsTime").val(),
            "newssrc": $("#newsSrc").val()
        }
        $.ajax({
            url:"server/insert.php",
            type:"post",/*ajax post方法提交*/
            data:jsonNews,
            datatype:"json",
            success:function(data){
                console.log(data);
            },
            error:function(XHR,textStatus,errorThrown){
                console.log(textStatus+"ready:"+XHR.readyState);
            }
        })
        
    });

php代码:

因为我们需要很多次调用php代码连接数据库,以后需要改动库名或者用户名等会很不方便,所以我们把连接数据库的操作单独提到一个文件中,比如命名为db.php:

//db.php

<?php
    header("Content-type:application/json;charset=utf-8");
    //error_reporting(0);
    $link = mysql_connect('localhost','name','pwd');
    if(!$link){
        echo json_encode(array('linkmsg'=>'false'));
    }else{
        mysql_select_db("testabc");
        mysql_query("SET NAMES utf8");
    }
?>

然后在其他php文件中直接调用这个文件:

//insert.php

<?php
    header("Content-type:application/json;charset=utf-8");
    require_once('db.php');

    if($link){
        //插入新闻
        $newstitle = addslashes(htmlspecialchars($_POST["newstitle"]));
        $newstype = $_POST["newstype"];
        $newsimg = $_POST["newsimg"];
        $newstime = $_POST["newstime"];
        $newssrc = $_POST["newssrc"];

        $sql = "INSERT INTO `news` (`newstitle`,`newstype`,`newsimg`,`newstime`,`newssrc`) VALUES ('{$newstitle}','{$newstype}','{$newsimg}','{$newstime}','{$newssrc}')";
        $result = mysql_query($sql,$link); 

        echo json_encode(array("success"=>"ok"));
    }

    mysql_close($link);
?>

3.删除一条数据:

//js代码删除一条数据
    var deleteId = null;
    $newsTbody.on("click",".btn-danger",function(e){
        $("#deleteModal").modal("show");/*模态框提示是否确认删除*/
        deleteId = $(this).parent().prevAll().eq(4).html();/*获取需要删除的数据的id*/
        console.log(deleteId);
    })
    $("#deleteModal #confirmDelete").click(function(e){
        if(deleteId){
            $.ajax({
                url: "server/delete.php",
                type: "post",/*post方法提交请求*/
                data:{"newsid":deleteId},
                success:function(data){
                    console.log("delete success");
                    $("#deleteModal").modal("hide");
                    refreshNews();
                }
            })
        }
    });

对应的php:

//delete.php
<?php
    header("Content-type:application/json;charset=utf-8");
    require_once('db.php');
    
    if($link){
        $newsid = $_POST["newsid"];/*获取id*/
        
        $sql = "DELETE FROM `news` WHERE `news`.`id`={$newsid}";/*组装删除命令*/
        $result = mysql_query($sql,$link);

        echo json_encode(array("delete"=>"success"));
    }

    mysql_close($link);
?>

4.修改一条数据:

//js代码修改新闻
    var updateId = null;
    $newsTbody.on("click",".btn-primary",function(e){
        $("#updateModal").modal("show");/*弹出模态框来给用户修改*/
        updateId = $(this).parent().prevAll().eq(4).html();/*获取修改的数据id*/
        
        $.ajax({
                url: "server/curnews.php",
                type: "get",/*get方法获取本条数据显示在模态框*/
                datatype:"json",
                data:{"newsid":updateId},
                success:function(data){
                    $("#unewsTitle").val(data[0].newstitle);
                    $("#unewsType").val(data[0].newstype);
                    $("#unewsImg").val(data[0].newsimg);
                    $("#unewsSrc").val(data[0].newssrc);
                    var utime = data[0].newstime.split(' ')[0];
                    $("#unewsTime").val(utime);                 
                }
                
            })
    })
    $("#updateModal #confirmUpdate").click(function(e){
        $.ajax({
            url: "server/update.php",
            type: "post",/*post方法将修改后的数据传回php*/
            data:{
                "newstitle":$("#unewsTitle").val(),
                "newstype":$("#unewsType").val(),
                "newsimg":$("#unewsImg").val(),
                "newstime":$("#unewsTime").val(),
                "newssrc":$("#unewsSrc").val(),
                "id":updateId
            },
            success:function(data){
                $("#updateModal").modal("hide");
                refreshNews();              
            }
            
        })
        
    });
//curnews.php

<?php
    header("Content-type:application/json;charset=utf-8");
    require_once('db.php');

    if($link){
        $newsid = $_GET["newsid"];
        //$newsid = 2;
        $sql = "SELECT * FROM `news` WHERE `id`={$newsid}";
        
        $result = mysql_query($sql,$link);
        
        $senddata = array();

        while($row = mysql_fetch_assoc($result)){
            array_push($senddata,array(
                    'id'=>$row['id'],
                    'newstype'=>$row['newstype'],
                    'newsimg'=>$row['newsimg'],
                    'newstime'=>$row['newstime'],
                    'newssrc'=>$row['newssrc'],
                    'newstitle'=>htmlspecialchars_decode($row['newstitle'])
                ));
        }
        echo json_encode($senddata);

    }

    mysql_close($link);
?>

//update.php

<?php
    header("Content-type:application/json;charset=utf-8");
    error_reporting(0);
    require_once('db.php');

    if($link){
        //插入新闻
        $newstitle = addslashes(htmlspecialchars($_POST["newstitle"]));
        $newstype = $_POST["newstype"];
        $newsimg = $_POST["newsimg"];
        $newstime = $_POST["newstime"];
        $newssrc = $_POST["newssrc"];
        $newsid = $_POST['id'];

        $sql = "UPDATE `news` SET `newstitle`='{$newstitle}',`newstype`='{$newstype}',`newsimg`='{$newsimg}',`newstime`='{$newstime}',`newssrc`='{$newssrc}' WHERE `id`={$newsid}";

        $result = mysql_query($sql,$link); 

        echo json_encode(array("success"=>"ok"));
    }
    mysql_close($link);
?>

 

以上就是php+mysql数据库的增删查改方案。

附几张页面参考,利用bootstrap完成:

增加:

删除:

修改:

 

 

 

 endding~

 

posted on 2016-12-06 15:19  魏日晗  阅读(961)  评论(0编辑  收藏  举报