建字段_添加数据_生成json.php

<?php
header("Content-Type:text/html;charset=utf8");

class db{
    
    static  $localhost = "localhost";
    static  $user = "root";
    static  $psw ="root";
    static  $db = "yunnan12316";
    
    public function conn() {
        $con = mysql_connect(self::$localhost, self::$user, self::$psw);
        mysql_query("set names utf8");
        mysql_select_db(self::$db, $con);
    }
    
    public function select($table) {
        $conn = $this->conn();
        $sql = "select * from ".$table; 
        $result = mysql_query($sql);
        while($row = mysql_fetch_array($result))
          {
            $data[] = $row;
          }
        $content['content'] = @$data;
        $json = json_encode($content);
        echo $json;
    }
    
    public function alter($table) {
        foreach ($_POST as $key => $value) {
            $array[] = "add " . $key . " varchar(220),";
        }
        $string = rtrim(implode(" ", $array), ",");
        $sql = "alter table ".$table." " . $string . "";
        mysql_query($sql);
    }
    
    public function add($table) {
        $conn = $this->conn();
        $conn = $this->alter($table);
        foreach ($_POST as $key => $value) {
            $k[] = $key;
            $v[] = "'" . $value . "'";
        }
        $key_db = implode(',', $k);
        $value_db = implode(',', $v);
        $sql = "INSERT INTO ".$table." (".$key_db.") VALUES (".$value_db.")";
        mysql_query($sql);
    }
    
}

$table = "test";
$db = new db();

if($_SERVER['REQUEST_METHOD']=='POST'){
    $db->add($table);
}else{
    $db->select($table);
}

 

posted @ 2016-09-27 09:21  fleam  阅读(770)  评论(0编辑  收藏  举报