thinkPHP框架实现的简单计算器示例


Posted in PHP onDecember 07, 2018

本文实例讲述了thinkPHP框架实现的简单计算器。分享给大家供大家参考,具体如下:

HTML部分 文件名 index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>计算器</title>
  <script type="text/javascript" src="public/js/jquery-2.2.3.js"></script>
  <link rel="stylesheet" href="public/css/index.css" rel="external nofollow" >
</head>
<body>
  <div class="login">
      <span>登录</span>
  </div>
  <div class="register">
      <form action="">
        <span>请输入你的手机号开始使用</span>
        <br><br>
        <input id="myphone" type="text">
        <input id="use" type="button" value="使用">
        <br><br>
      </form>
  </div>
  <div class="calculator">
      <div class="counter">
        <span class="brand">计算器</span>
        <br><br>
        <input class="import" type="text" style="text-align: right;">
        <br><br>
        <form class="snap" action="">
          <br><br>
          <input class="order" id="one" type="button" value="1">
          <input class="order" id="two" type="button" value="2">
          <input class="order" id="three" type="button" value="3">
          <input class="order" id="four" type="button" value="4">
          <input class="order" id="five" type="button" value="5">
          <br><br>
          <input class="order" id="six" type="button" value="6">
          <input class="order" id="seven" type="button" value="7">
          <input class="order" id="eight" type="button" value="8">
          <input class="order" id="nine" type="button" value="9">
          <input class="order" id="zero" type="button" value="0">
          <br><br>
          <input class="operator" id="plus" type="button" value="+">
          <input class="operator" id="add" type="button" value="-">
          <input class="operator" id="mul" type="button" value="*">
          <input class="operator" id="sub" type="button" value="/">
          <input class="" id="equal" type="button" value="=">
          <br><br>
          <input class="order" type="button" value=".">
          <input id="backspace" type="button" value="←">
          <input id="clear" type="button" value="c">
          <input type="button" value="CE">
          <input type="button" value="MC">
        </form>
      </div>
      <div class="result">
        <div>
          <span>当前结果:</span><span id="current_results"></span>
        </div>
        <br><br>
        <span>历史记录:</span>
        <ul id="cal_result" style="list-style-type: none">
          <li><span>删除</span></li>
        </ul>
      </div>
  </div>
</body>
  <script type="text/javascript" src="public/js/index.js">
  </script>
</html>

CSS样式 文件名 index.css

.login{/*登录*/
  height: 30px;
  width: 100px;
  background-color: #00a2d4;
  text-align: center;
  cursor: pointer;
  padding-top: 10px;
  position: fixed;
}
.register{
  display: none;
  position: fixed;
}
.calculator{
  display: none;
  position: fixed;
}
.counter{
  border: 1px solid black;
  height: 400px;
  width: 320px;
  float: left;
}
.import{
  height: 20px;
  width: 180px;
  margin-top: 50px;
  margin-left: 50px;
}
.snap{
  margin-left: 50px;
  margin-top: -30px;
}
.snap input{
  height: 30px;
  width: 30px;
}
.result{
  border: 1px solid black;
  height: 400px;
  width: 320px;
  float: left;
  margin-left: 50px;
}
.brand{
  position: relative;
  top: 50px;
  left: 90px;
}

JS部分  文件名 index.js

//计算屏幕宽高
var w_width = $(window).width();
var w_height = $(window).height();
var operator = 0;//运算符号
var change = 0;//属于运算符后需要清空上一数值
var num1 = 0;//元算的第一个数据
var num2 = 0;//运算的第二个数据
var sum = 0;//运算结果
//居中
function setCenter(obj){
  var this_width = $(obj).width();
  var this_height = $(obj).height();
  var this_left = parseInt((w_width-this_width)/2);
  var this_height = parseInt((w_height-this_height)/2);
  $(obj).css({left:this_left,top:this_height});
}
//正则
function testReg() {
  //定义参数
  var regType = arguments[0]?arguments[0]:'phone';
  var myString = arguments[1]?arguments[1]:false;
  var regArray = new Array();
  regArray['phone'] = /^1[3|4|5|7|8]\d{9}$/;
  regArray['email'] = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;//邮箱 *代表{0,} +代表{1,} ?代表{0,1}
  //判断
  if (myString){
    return regArray[regType].test(myString);
  }
  return false;
}
//发送数据到后台
function sendMessage() {
  //手机号
  var myphone = $("#myphone").val();
  //计算器
  var myUrl = '/app/base.php';
  var myData = {num1:num1,num2:num2,cal_option:operator,cal_result:sum,myphone:myphone,type:'add'};
  $.post(myUrl,myData,function (msg) {
    //TODO
  },'json')
  getResultByPhone();
}
//获取结果
function getResultByPhone() {
  var myphone = $("#myphone").val();
  var myUrl = '/app/base.php';
  var myData = {myphone:myphone,type:'getResult'};
  $.post(myUrl,myData,function (msg) {
    //TODO
    $("#cal_result").html(msg);
  },'text')
}
//获取数据
function deleteHistory(id) {
  var myUrl = '/app/base.php';
  var MyData = {id:id,type:'delete'};
  $.post(myUrl,MyData,function (msg) {
    //TODO
  },'json')
  getResultByPhone();
}
$(function () {
  //登录居中
  setCenter($(".login").show(8000));
  //点击登录显示输入
  $(".login").click(function(){
    setCenter($(".register").show());
    $(this).hide();
  });
  //点击使用显示计算器
  $("#use").click(function () {
    if (testReg('phone',$("#myphone").val())){
      setCenter($(".calculator").show());
      $(".register").hide();
      getResultByPhone()
    }else {
      alert ("你输的手机格式不对");
      return false;
    }
  })
  $(".order").click(function () {//点击数字
    var num = $(this).val();
    var oldValue = $(".import").val();
    if (change ==1){
      oldValue = "0";
      change = 0;
    }
    var newValue = "";
    if (num == -1){
      oldValue = parseFloat(oldValue);
      newValue = oldValue * -1;
    }else if (num == "."){
      if (oldValue.indexOf('.') == -1)
        newValue = oldValue + ".";
      else
        newValue = oldValue;
    }else {
      if (oldValue == 0 && oldValue.lastIndexOf('.') == -1){
        newValue = num;
      }else {
        newValue = oldValue + num;
      }
    }
    $(".import").val(newValue);
  });
  $("#clear").click(function () {//清除
    $(".import").val("0");
    operator = 0;
    change = 0;
    num1 = 0;
    num2 = 0;
  });
  $("#backspace").click(function () {//退格
    if (change ==1){
      operator = 0;
      change = 0;
    }
    var value = $(".import").val();
    if (value.length == 1){
      $(".import").val("0");
    }else {
      value = value.substr(0,value.length - 1);
      $(".import").val(value);
    }
  });
  $(".operator").click(function() {//点击运算符号触发事件
    change = 1;
    operator = $(this).val();
    var value = $(".import").val();
    var dianIndex = value.indexOf(".");
    if (dianIndex == value.length) {
      value = value.substr(0, value.length - 1);
    }
    num1 = parseFloat(value);
  });
  $("#equal").click(function () {//点击等号
    var value = $(".import").val();
    var dianIndex = value.indexOf(".");
    if (dianIndex == value.length){
      value = value.substr(0,value.length - 1);
    }
    var equal = $(this).val();
    num2 = parseFloat(value);
    if (operator == "+"){
      sum = num1 + num2;
    }else if (operator == "-"){
      sum = num1 - num2;
    }else if (operator == "*"){
      sum = num1 * num2;
    }else if (operator == "/"){
      sum = num1 / num2;
    }else if (operator == "" || num1 ==0 || num2 == 0){
      sum = num1 +num2;
    }
    var re = /^[0-9]+.?[0-9]*$/;
    if (re.test(sum)){
      sum = sum.toFixed(2);
    }
    $(".import").val(sum);
    sendMessage();
    $("#current_results").text(num1 + operator + num2 + equal + sum);
    change = 1;
    operator = 0;
    num1 = 0;
    num2 = 0;
  });
})

接口 文件名 IDB.php

<?php
namespace mao;
interface IDB{
  public function insert($data);
  public function update($data);
  public function select($data);
  public function del($data);
}

创建一个Mysqli类继承接口实现增删改查

文件名 MySqli.clsaa.php

<?php
namespace mao;
include "IDB.php";
class MySqli implements IDB{
  private $conn = null;
  private $table = null;
  private $sysConfig = array(
    'host' => '',
    'user' => '',
    'pwd' => '',
    'db' => ''
  );
  private static $_instance = null;
  private function __construct($config){
    if(is_array($config)){
      $this->sysConfig = array_merge($this->sysConfig,$config);
      $this->conn = new \Mysqli($this->sysConfig['host'],$this->sysConfig['user'],$this->sysConfig['pwd'],$this->sysConfig['db']);
      if (!$this->conn){
        echo "连接失败".mysqli_error();
      }
    }
  }
  public static function getInstance($config){
    if (is_null(self::$_instance)){
      self::$_instance = new self($config);
    }
    return self::$_instance;
  }
  //设计表
  public function table($table){
    $this->table = $table;
    return $this;
  }
  //查询
  private function changeCondition($condition){
    $where_array = array();
    foreach($condition as $k => $v){
      if(is_array($v)){
        if(strtolower($v[0])=='like'){
          $where_array[] = $k.' '.$v[0].' \'%'.$v[1].'%\'';
        }else{
          $where_array[] = $k.' '.$v[0].' \''.$v[1].'\'';
        }
      }
      if(is_string($v)){
        $where_array[] = $k.' = \''.$v.'\'';
      }
    }
    $where = implode(' AND ',$where_array);
    return $where?$where:1;
  }
  public function select($condition){
    $where = $this->changeCondition($condition);
    $sql = "select * from $this->table where ".$where."order by id desc limit 10";
    $res = $this->conn->query($sql);
    $ret = array();
    while ($row = $res->fetch_assoc()){
      $ret[] = $row;
    }
    return $ret;
  }
  public function insert($data){
    $sql = "insert into `{$this->table}` ( `id` ,`user_phone` ,`num1` ,`num2` ,`option` ,`result` ,`status` ,`admin_user` ) VALUES ( NULL , '{$data['myphone']}', '{$data['num1']}', '{$data['num2']}', '{$data['cal_option']}', '{$data['cal_result']}', '1', 'mao' )";
    $this->conn->query($sql);
  }
    public function update($id){
    $sql = "UPDATE `{$this->table}` SET `status` = '-1' WHERE `id` ={$id}";
    $this->conn->query($sql);
  }
  public function del($condition){
  }
}

配置项  文件名 config.php

<?php
return [
  'db'=>[
    'host' => '127.0.0.1',
    'user' => 'root',
    'pwd' => 'root',
    'db' => 'cal'
  ],
  'author' =>[
    'adminuser' => 'mao',
  ]
];

操作计算器 文件名 base.php

<?php
namespace mao;
define("ROOT_PATH",dirname(dirname(__FILE__)));
$config = include ROOT_PATH."/lib/config/config.php";
include ROOT_PATH."/lib/db/MySqli.class.php";
$db = MySqli::getInstance($config['db']);
if ($_POST){
  //查询
  if ($_POST['type'] == 'getResult'){
    $condition = array(
      'user_phone' =>array('like',$_POST['myphone']),
      'status'=> '1'
    );
    $result = $db->table('calculate')->select($condition);
    $result_string = '';
    foreach ($result as $k => $v){
      $result_string .= "<li><span class='mydelte' onclick='deleteHistory({$v['id']})'>删除</span>{$v['num1']} {$v['option']} {$v['num2']} = {$v['result']} </li>";
    }
    echo $result_string;
  }
  //删除
  if ($_POST['type'] == 'delete'){
    $id = isset($_POST['id'])?$_POST['id']:'';
    $db->table('calculate')->update($id);
  }
  if ($_POST['type'] == 'add'){
    $data = $_POST;
    $db->table('calculate')->insert($data);
  }
}

目录结构

thinkPHP框架实现的简单计算器示例

sql语句

SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- ?料?? `cal`
--
-- --------------------------------------------------------
--
-- 表的??? `calculate`
--
CREATE TABLE IF NOT EXISTS `calculate` (
 `id` int(10) NOT NULL AUTO_INCREMENT COMMENT '序号 主键 自增',
 `user_phone` varchar(100) NOT NULL COMMENT '用户手机号',
 `num1` varchar(100) NOT NULL COMMENT '第一个数字',
 `num2` varchar(100) NOT NULL COMMENT '第二个数字',
 `option` varchar(10) NOT NULL COMMENT '加减乘除选项',
 `result` varchar(100) NOT NULL COMMENT '结果',
 `status` int(10) NOT NULL COMMENT '状态-1 删除 0 禁用 1 正常',
 `admin_user` varchar(100) NOT NULL COMMENT '管理员',
 PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='计算表' AUTO_INCREMENT=40 ;
--
-- ?存?料表中的?料 `calculate`
--
INSERT INTO `calculate` (`id`, `user_phone`, `num1`, `num2`, `option`, `result`, `status`, `admin_user`) VALUES
(1, '15727228076', '', '', '', '', 0, ''),
(2, '15727228076', '7', '6', '+', '13', -1, 'jingshan'),
(3, '13880425377', '9', '6', '+', '15', -1, 'jingshan'),
(4, '13880425377', '8', '7', '+', '15', -1, 'jingshan'),
(5, '13880425377', '8', '9', '*', '72', -1, 'jingshan'),
(6, '13880425377', '6', '7', '+', '13', 1, 'jingshan'),
(7, '13880425377', '89', '7', '+', '96', -1, 'jingshan'),
(8, '13880425377', '67', '8', '+', '75', 1, 'jingshan'),
(9, '13880425377', '2', '7', '+', '9', 1, 'jingshan'),
(10, '13880425377', '78', '7', '+', '85', 1, 'jingshan'),
(11, '13880425377', '12', '9', '*', '108', 1, 'jingshan'),
(12, '13880425377', '23', '7', '-', '16', 1, 'jingshan'),
(13, '13880425377', '67', '2', '-', '65', 1, 'jingshan'),
(14, '13880425377', '34', '7', '+', '41', 1, 'jingshan'),
(15, '13880425377', '78', '8', '/', '9.75', 1, 'jingshan'),
(16, '13880425377', '72', '9', '+', '81', 1, 'jingshan'),
(17, '13880425377', '78', '9', '+', '0', 1, 'mao'),
(18, '13880425377', '67', '9', '+', '0', 1, 'mao'),
(19, '13880425377', '78', '9', '+', '0', 1, 'mao'),
(20, '13880425377', '78', '9', '+', '0', 1, 'mao'),
(21, '13880425377', '67', '8', '+', '0', 1, 'mao'),
(22, '13880425377', '62', '8', '+', '0', 1, 'mao'),
(23, '13880425377', '12', '9', '*', '0', 1, 'mao'),
(24, '13880425377', '12', '9', '+', '0', 1, 'mao'),
(25, '13880425377', '7', '8', '-', '0', 1, 'mao'),
(26, '13880425377', '2', '4', '+', '0', 1, 'mao'),
(27, '13880425377', '8', '9', '*', '0', 1, 'mao'),
(28, '13880425377', '8', '9', '+', '0', 1, 'mao'),
(29, '13880425377', '12', '9', '*', '108.00', 1, 'mao'),
(30, '13880425377', '7', '8', '+', '15.00', 1, 'mao'),
(31, '13880425377', '1', '9', '*', '9.00', 1, 'mao'),
(32, '13880425377', '29', '7', '*', '203.00', 1, 'mao'),
(33, '13880425377', '95', '8', '/', '11.88', 1, 'mao'),
(34, '13880425377', '67', '98', '*', '6566.00', 1, 'mao'),
(35, '13880425377', '22', '9', '-', '13.00', 1, 'mao'),
(36, '13880425377', '45', '9', '/', '5.00', 1, 'mao'),
(37, '13880425377', '555', '777', '+', '1332.00', 1, 'mao'),
(38, '13880425377', '89', '0', '-', '89.00', 1, 'mao'),
(39, '13880425377', '0', '89', '0', '89.00', 1, 'mao');
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
---------------------

希望本文所述对大家基于ThinkPHP框架的PHP程序设计有所帮助。

PHP 相关文章推荐
深入理解ob_flush和flush的区别(ob_flush()与flush()使用方法)
Feb 06 PHP
关于PHP session 存储方式的详细介绍
Jun 25 PHP
phpmailer中文乱码问题的解决方法
Apr 22 PHP
php中strtotime函数用法详解
Nov 15 PHP
php比较相似字符串的方法
Jun 05 PHP
PHP解压tar.gz格式文件的方法
Feb 14 PHP
PHP实现文件上传与下载实例与总结
Mar 13 PHP
PHP请求Socket接口测试实例
Aug 12 PHP
PHP实现递归目录的5种方法
Oct 27 PHP
PHP实现求连续子数组最大和问题2种解决方法
Dec 26 PHP
php通过各种函数判断0和空
Jul 04 PHP
PHP使用pdo实现事务处理操作示例
Sep 05 PHP
PHP实现的简单留言板功能示例【基于thinkPHP框架】
Dec 07 #PHP
laravel5使用freetds连接sql server的方法
Dec 07 #PHP
php多进程模拟并发事务产生的问题小结
Dec 07 #PHP
Ubuntu 16.04中Laravel5.4升级到5.6的步骤
Dec 07 #PHP
PHP ajax+jQuery 实现批量删除功能实例代码小结
Dec 06 #PHP
PHP实现简易计算器功能
Aug 28 #PHP
laravel5实现微信第三方登录功能
Dec 06 #PHP
You might like
使用Apache的htaccess防止图片被盗链的解决方法
2013/04/27 PHP
如何使用PHP获取指定日期所在月的开始日期与结束日期
2013/08/01 PHP
PHP程序漏洞产生的原因分析与防范方法说明
2014/03/06 PHP
php调用淘宝开放API实现根据卖家昵称获取卖家店铺ID的方法
2015/07/29 PHP
点击下载链接 弹出页面实现代码
2009/10/01 Javascript
JQuery 获得绝对,相对位置的坐标方法
2010/02/09 Javascript
js自定义事件及事件交互原理概述(一)
2013/02/01 Javascript
jQuery+CSS实现菜单滑动伸展收缩(仿淘宝)
2013/03/22 Javascript
jquery实现的蓝色二级导航条效果代码
2015/08/24 Javascript
jQuery简单实现仿京东商城的左侧菜单效果代码
2015/09/09 Javascript
jQuery实现切换页面过渡动画效果
2015/10/29 Javascript
快速获取/设置iframe内对象元素的几种js实现方法
2016/05/20 Javascript
微信小程序 wx.request(object) API详解及实例代码
2016/09/30 Javascript
jQuery Easy UI中根据第一个下拉框选中的值设置第二个下拉框是否可以编辑
2016/11/29 Javascript
如何获取元素的最终background-color
2017/02/06 Javascript
从零学习node.js之搭建http服务器(二)
2017/02/21 Javascript
JavaScript实现的商品抢购倒计时功能示例
2017/04/17 Javascript
JavaScript比较两个数组的内容是否相同(推荐)
2017/05/02 Javascript
JS Object.preventExtensions(),Object.seal()与Object.freeze()用法实例分析
2018/08/25 Javascript
vue.js响应式原理解析与实现
2020/06/22 Javascript
解决vue keep-alive 数据更新的问题
2018/09/21 Javascript
小程序云开发实战小结
2018/10/25 Javascript
在Vue项目中使用jsencrypt.js对数据进行加密传输的方法
2019/04/17 Javascript
详解微信小程序实现跑马灯效果(附完整代码)
2019/04/29 Javascript
python异步任务队列示例
2014/04/01 Python
python实现Flappy Bird源码
2018/12/24 Python
在Python中将函数作为另一个函数的参数传入并调用的方法
2019/01/22 Python
python之array赋值技巧分享
2019/11/28 Python
如何开发一款堪比APP的微信小程序(腾讯内部团队分享)
2016/12/22 HTML / CSS
Square Off美国/加拿大:世界上最聪明的国际象棋棋盘
2018/12/06 全球购物
如何写一份好的英文求职信
2014/03/19 职场文书
财务内勤岗位职责
2014/04/17 职场文书
2014年学习全国道德模范事迹思想汇报
2014/09/15 职场文书
乡镇党的群众路线教育实践活动个人整改方案
2014/10/31 职场文书
学校社团活动总结
2015/05/07 职场文书
医院中层管理人员培训心得体会
2016/01/11 职场文书