php 数据库 操作

 

header.php

<?php
error_reporting(0);//加上error_reporting(0);就不会弹出警告了  
// header("Content-type:text/html;charset=utf-8");
// header('Content-Type:application/x-www-form-urlencoded; charset=utf-8');

header('Content-Type:application/json; charset=utf-8');
header("Access-Control-Allow-Origin:*");

header('Access-Control-Allow-Methods:POST');

header('Access-Control-Allow-Headers:x-requested-with, content-type');
ini_set("error_reporting","E_ALL & ~E_NOTICE");

?>

 

comm.php

<?php
class database {
  var $servername = "127.0.0.1";
  var $username = "root";
  var $password = "123456";
  var $dbname = "database";
  var $conn;

  function openConn() {
    // 创建连接
    $this->conn = new mysqli($this->servername, $this->username, $this->password, $this->dbname);
    
    // Check connection
    if ($this->conn->connect_error) {
      die("连接失败: " . $this->conn->connect_error);
    } 
    mysqli_query($this->conn, "set names utf8"); //**设置字符集***
  }

  function closeConn() {
    $this->conn->close();
  }

  function __construct() {
    $this->openConn();
  }

  function __destruct() {
      $this->closeConn();
  }

  function select($sqlStr)
  {
    // $sql = "SELECT * FROM person";
    $sql = $sqlStr;
    $result = $this->conn->query($sql);
    
    $arr1 = array();
    if ($result->num_rows > 0) {
        // 输出数据
        while($row = $result->fetch_assoc()) {
          array_push($arr1, $row);
        }
    }

    // return $arr1;

    $object = (object) [
      'data' => $arr1,
      "status" => 20
    ];
    
    print_r(json_encode($object));
  }

  function update($sqlStr) {
    if (mysqli_query($this->conn, $sqlStr)) {
      $object = (object) [
        "status" => 20
      ];
    } else {
      $object = (object) [
        "status" => 40
      ];
    }
    print_r(json_encode($object));
  }
}

?>

 

select.php

<?php
include 'header.php';
include 'comm.php';
$d = new database();
$d->select("SELECT * FROM person");
?>

 

update.php

<?php
include 'header.php';
include 'comm.php';

$id = $_POST['id'];
$username = $_POST['username'];
$userpass = $_POST['userpass'];

$sql = "UPDATE person SET 
username='$username',
userpass='$userpass'
 WHERE id = '$id'";

$d = new database();
$d->update($sql);

?>

 

insert.php

<?php
include 'header.php';
include 'comm.php';

$username = $_POST['username'];
$userpass = $_POST['userpass'];
$sql = "INSERT INTO person (username, userpass) VALUES ('$username', '$userpass')";
 
$d = new database();
$d->update($sql);
?>

 

delete.php

<?php
include 'header.php';
include 'comm.php';

$id = $_POST['id'];
$sql = "DELETE FROM person WHERE id = '$id'";

$d = new database();
$d->update($sql);
 
?>

 

字符集: utf8 -- UTF-8 Unicode

排序规则: utf8_general_ci

posted @ 2019-09-27 12:03  彭成刚  阅读(239)  评论(0编辑  收藏  举报