原生php实现账单功能

由于合租,在一块做饭缴纳水电费等等这样的消费,为了公开透明,我专门花一下午做了一个账单记录的小demo,相关的消费力求做到公开透明

这个项目做完复习了并且学到了很多东西,挺有成就感。

代码:
add.php

<?php
class MYSQL
{
    private static $conn =false ;
    protected $config = array(
//      "host" =>'127.0.0.1',
      "host" =>'mysql',
      "database"=>"mall",
      "user"=>"root",
      "password"=>"123456",
      "port"=>3306
    );

    private function __construct()
    {
        $this->conn = mysqli_connect($this->config['host'],$this->config['user'],$this->config['password'],$this->config['database']);

        $this->conn or die("mysql_connect error".mysqli_error($this->conn));
        mysqli_query("SET NAMES utf8");
    }

    public static function getInstance()
    {
        if (self::$conn instanceof self){
            return self::$conn;
        }
        return new self();
    }

    private function __clone()
    {
        // TODO: Implement __clone() method.
    }

    public function fetchAll($table)
    {
        $sql    = "select * from {$table}";
        $data   = mysqli_query($this->conn,$sql);
        $result = mysqli_fetch_all($data,MYSQLI_ASSOC);
//        var_dump($result);
        $result =array(
            "code"=>1,
            "message"=>'success',
            "data"=>$result
        );
        exit(json_encode($result));
    }

    public function add($table , $data)
    {
        $key_str   = "";
        $value_str = "";
        foreach ($data as $key =>$value)
        {
           if (empty($value))
           {
               die("插入失败");
           }
            $key_str     .=$key.",";
            $value_str   .="'{$value}'".",";
        }

        $key_str     = trim($key_str,',');
        $value_str   = trim($value_str,',');
        $sql = "insert into {$table} ($key_str) values ($value_str)";
//        echo $sql;
        $insert_id = mysqli_query($this->conn,$sql);

//        echo $insert_id;
        if ($insert_id)
        {
            return $insert_id;
        }
        return false;
    }
}

$type = $_POST['type']?$_POST['type']:1;
$tableName = "consumelog";
if ($type ==1)
{
    MYSQL::getInstance()->fetchAll($tableName);
} else{
    $data = array(
      'photo'=> uplod(),
      'money'=> $_POST['money'],
      'goodName'=>$_POST['goodName'],
      'add_time'=>time()
    );
    $re = MYSQL::getInstance()->add($tableName,$data);
    header("location:http://localhost/layui/upload.html");
    /*$result =array(
        "code"=>1,
        "message"=>'success',
        "data"=>$re
    );
    exit(json_encode($result));*/
}
function uplod()
{
    $file = $_FILES['file'];//得到传输的数据

//得到文件名称
    $name = $file['name'];
    $type = strtolower(substr($name,strrpos($name,'.')+1)); //得到文件类型,并且都转化成小写
    $allow_type = array('jpg','jpeg','gif','png'); //定义允许上传的类型
//判断文件类型是否被允许上传
    if(!in_array($type, $allow_type)){
        //如果不被允许,则直接停止程序运行
        return ;
    }
//判断是否是通过HTTP POST上传的
    if(!is_uploaded_file($file['tmp_name'])){
        //如果不是通过HTTP POST上传的
        return ;
    }
    $upload_path = "./upload/"; //上传文件的存放路径
//开始移动文件到相应的文件夹
    if(move_uploaded_file($file['tmp_name'],$upload_path.$file['name'])){
       return $upload_path.$file['name'];
    }else{
      return ;
    }

}

upload.html

<html>
<head>
    <title>消费账单</title>
    <meta charset="UTF-8">
</head>
<style>
    table{
        border: 1px solid #0C0C0C;
        height: 100px;
        margin-top: 20px;

    }
    table th{
        border: 1px solid #0C0C0C;
    }
    table td {
        border: 1px solid #0C0C0C;
        text-align: center;
        cellspacing:"0" ;
        cellpadding:"0";
        height: 60px;
        width: 100px;
    }
</style>
<style>
    #userinfo{
        display: inline-block;
        background: inherit
    }
    #userinfo form{
        margin-bottom: 10px;
    }
    #userinfo form label{
        font-size: 15px !important;
        font-weight: 600;
    }
    #change{
        position:absolute;
        top:0;
        left:0;
        width:100%;
        height:100%;
        background:rgba(0,0,0,0.4);
    }
    #change>.box{
        width:36%;
        position: relative;
        left:32%;
        top:30%;
        background: #FFFFFF;
    }
    #change>.box .title{
        line-height: 2rem;
        padding: 0 1rem;
        color: #FFFFFF;
        background: #023052;
        font-weight: bold;
    }
    #change>.box .main{
        padding: 1rem 2rem;
    }
    #change>.box .input{
        line-height: 4rem;
        border-bottom: 1px dashed #e2e2e2
    }
    #change>.box .input .tips{
        color: red;
        margin-left: 1rem;
    }
    #change>.box .main button{
        outline: none;
        border: none;
        color: #ffffff;
        background: #1ba194;
        padding: 0.5rem;
        margin: 1rem 4rem;
    }
</style>
<body>
<div>
    <div style="float: right; padding: 20px 15%;" >
        <button onclick="change(1)" >添加记录</button>
    </div>
    <div align="center">
    <h1>账单记录</h1>
    <table width="70%"  cellspacing="0" cellpadding="0" id="record">
        <tr>
            <th>id</th>
            <th>凭证</th>
            <th>消费</th>
            <th>购买商品</th>
            <th>添加时间</th>
        </tr>

    </table>
    </div>

</div>
<!--------------------------------------------------------------------------------->
            <div id="change" style="display:none;">
                <div class="box">
                    <form id="upload" method="post" enctype="multipart/form-data" action="http://localhost/layui/add.php">
                        <p class="title">
                            添加账单
                            <span style="float: right;" onclick="box_close(1)">x</span>
                        </p>
                        <div class="main">
                            <span style="color: #023052;font-weight: bold;">新增记录</span>
                            <div class="input">
                                <span>商品名称:</span>
                                <input type="txt" name="goodName" id="" value="" />
                            </div>
                            <div class="input">
                                <span>商品价格:</span>
                                <input type="txt" name="money" id="" value="" />
                            </div>
                            <div class="input">
                                <span>凭证:</span>
                                <input type="file" name="file" id="" value="" />
                            </div>
                            <input type="hidden" name="type"  value="2" />
                            <button type="submit" onclick="box_close()">确定</button>
                        </div>
                    </form>
                </div>
            </div>
<!--------------------------------------------------------------------------------->

<script>
    function change(value){
       // document.getElementById("userid").attr({value:value})
       //  $('#change').css("display","block");
        document.getElementById("change").style.display = "block";
    }
    function box_close(a){
        if (a)
        {
            document.getElementById("change").style.display = "none";
        }

    }

    //将时间戳转换成正常时间格式
    function timestampToTime(timestamp) {
        var date = new Date(timestamp * 1000);//时间戳为10位需*1000,时间戳为13位的话不需乘1000
        var Y = date.getFullYear() + '-';
        var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
        var D = date.getDate() + ' ';
        var h = date.getHours() + ':';
        var m = date.getMinutes() + ':';
        var s = date.getSeconds();
        return Y+M+D+h+m+s;
    }

    function httpRequest(obj,successfun,errFun){
        var xmlHttp = null;
        //创建 XMLHttpRequest 对象,老版本的 Internet Explorer (IE5 和 IE6)使用 ActiveX 对象:xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
        if(window.XMLHttpRequest){
            //code for all new browsers
            xmlHttp = new XMLHttpRequest;
        }else if(window.ActiveXObject){
            //code for IE5 and IE6
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        //判断是否支持请求
        if(xmlHttp == null){
            alert("浏览器不支持xmlHttp");
            return;
        }
        //请求方式, 转换为大写
        var httpMethod = (obj.method || "Get").toUpperCase();
        //数据类型
        var httpDataType = obj.dataType||'json';
        //url
        var httpUrl = obj.url || '';
        //异步请求
        var async = true;
        //post请求时参数处理
        if(httpMethod=="POST"){
            //请求体中的参数 post请求参数格式为:param1=test&param2=test2
            var data = obj.data || {};
            var requestData = '';
            for(var key in data){
                requestData = requestData + key + "=" + data[key] + "&";
            }
            if(requestData == ''){
                requestData = '';
            }else{
                requestData = requestData.substring(0,requestData.length - 1);
            }
            // console.log(requestData);
        }
        //onreadystatechange 是一个事件句柄。它的值 (state_Change) 是一个函数的名称,当 XMLHttpRequest 对象的状态发生改变时,会触发此函数。状态从 0 (uninitialized) 到 4 (complete) 进行变化。仅在状态为 4 时,我们才执行代码
        xmlHttp.onreadystatechange = function(){
            //complete
            if(xmlHttp.readyState == 4){
                if(xmlHttp.status == 200){
                    //请求成功执行的回调函数
                    successfun(xmlHttp.responseText);
                }else{
                    //请求失败的回调函数
                    errFun;
                }
            }
        }
        //请求接口
        if(httpMethod == 'GET'){
            xmlHttp.open("GET",httpUrl,async);
            xmlHttp.send(null);
        }else if(httpMethod == "POST"){
            xmlHttp.open("POST",httpUrl,async);
            xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
            xmlHttp.send(requestData);
        }
    }
    httpRequest({
        method:"post",
        url:"http://localhost/layui/add.php",//请求的url地址
        data:{
            'type':1
        }
    },function(res){

            res = JSON.parse(res);
        // console.log(res.data)
        for (var i=0;i<res.data.length;i++)
         {
             t =timestampToTime(res.data[i].add_time)
                   document.getElementById("record").innerHTML +="  <tr>\n" +
                   "            <td>"+res.data[i].id+"</td>\n" +
                   "            <td><img width='90' src='"+res.data[i].photo+" '/></td>\n" +
                   "            <td>"+res.data[i].money+"</td>\n" +
                   "            <td>"+res.data[i].goodName+"</td>\n" +
                   "            <td>"+t+"</td>\n" +
                   "        </tr>";
         }
    },function(){
        console.log("请求失败");
    });

</script>
</body>
</html>

效果图:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/kevlin_V/article/details/104691180