由於合租,在一塊做飯繳納水電費等等這樣的消費,爲了公開透明,我專門花一下午做了一個賬單記錄的小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¶m2=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>
效果圖: