1、HTTP协议作业: 自己封装一个myfopen的方法,能够通过它去用 get , post , head 方法请求 ,
并能根据不同的返回状态码给出不同的提示

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
$post = array('name' => 'post', 'url' => 'me.eluup.com');
$cookie = array('name' => 'cookie', 'url' => 'me.eluup.com');
$header = array('name' => 'header', 'url' => 'me.eluup.com');
$fetch_type_list = array('quest', 'content', 'header', 'status', 'all');
 
$fetch_type = $fetch_type_list[array_rand($fetch_type_list, 1)];
$data = myfopen($url, $post, $cookie, $header, $fetch_type);
var_dump($data);
 
 
function myfopen($url, $post = '', $cookie = '', $header = '', $fetch_type = 'content', $limit = 0,$bysocket = FALSE, $ip = '', $timeout = 15, $block = TRUE) {
    $fetch_type = strtolower($fetch_type);
    $fetch_type_list = array('quest', 'content', 'header', 'status', 'all');
    in_array($fetch_type, $fetch_type_list) || $fetch_type = 'content';
    $respond_content = '';
    $respond_header = array();
    $matches = parse_url($url);
    !isset($matches['host']) && $matches['host'] = '';
    !isset($matches['path']) && $matches['path'] = '';
    !isset($matches['query']) && $matches['query'] = '';
    !isset($matches['port']) && $matches['port'] = '';
    $host = $matches['host'];
    $path = $matches['path'] ? $matches['path'].($matches['query'] ? '?'.$matches['query'] : '') : '/';
    $port = !empty($matches['port']) ? $matches['port'] : 80;
     
    if ($post && function_exists('parse_post')) {
        $post = parse_post($post);
    }
    if ($header && function_exists('parse_header')) {
        $header = parse_header($header);
    }
    if ($cookie && function_exists('parse_post')) {
        $cookie = parse_post($cookie);
    }
    if($post) {
        $out = "POST $path HTTP/1.0\r\n";
        $out .= "Accept: */*\r\n";
        //$out .= "Referer: $boardurl\r\n";
        $out .= "Accept-Language: zh-cn\r\n";
        $out .= "Content-Type: application/x-www-form-urlencoded\r\n";
        $out .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n";
        $out .= "Host: $host\r\n";
        $out .= 'Content-Length: '.strlen($post)."\r\n";
        $out .= "Connection: Close\r\n";
        $out .= "Cache-Control: no-cache\r\n";
        $out .= "Cookie: $cookie\r\n";
        $header && $out .= $header . "\r\n";
        $out .= "\r\n";
         
        $out .= $post;
    } else {
        $out = "GET $path HTTP/1.0\r\n";
        $out .= "Accept: */*\r\n";
        //$out .= "Referer: $boardurl\r\n";
        $out .= "Accept-Language: zh-cn\r\n";
        $out .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n";
        $out .= "Host: $host\r\n";
        $out .= "Connection: Close\r\n";
        $header && $out .= $header . "\r\n";
        $out .= "Cookie: $cookie\r\n";
        $header && $out .= $header . "\r\n";
        $out .= "\r\n";
    }
    if ('quest' == $fetch_type) {
        return $out;
    }
    if(function_exists('fsockopen')) {
        $fp = @fsockopen(($ip ? $ip : $host), $port, $errno, $errstr, $timeout);
    } elseif (function_exists('pfsockopen')) {
        $fp = @pfsockopen(($ip ? $ip : $host), $port, $errno, $errstr, $timeout);
    } else {
        $fp = false;
    }
     
    if(!$fp) {
        return '';
    } else {
        stream_set_blocking($fp, $block);
        stream_set_timeout($fp, $timeout);
        @fwrite($fp, $out);
        $status = stream_get_meta_data($fp);
        $is_onec = TRUE;
        if(!$status['timed_out']) {
            while (!feof($fp)) {
                if(($line = @fgets($fp)) && ($line == "\r\n" ||  $line == "\n")) {
                    break;
                } else {
                    if ($is_onec) {
                        $respond_status = explode(" ", substr($line, 0, strlen($line) - 2));
                        if ('status' == $fetch_type) {
                            @fclose($fp);
                            return $respond_status;
                        }
                        $is_onec = FALSE;
                    } else {
                        $cutpos = strpos($line, ":");
                        $respond_header[] = array(
                            'attr' => substr($line, 0, $cutpos),
                            'val' => substr($line, $cutpos + 2, strlen($line) - 4 - $cutpos),
                        );
                    }
                }
            }
            if ('header' == $fetch_type) {
                @fclose($fp);
                return $respond_header;
            }
             
             
            $stop = false;
            while(!feof($fp) && !$stop) {
                $data = fread($fp, ($limit == 0 || $limit > 8192 ? 8192 : $limit));
                $respond_content .= $data;
                if($limit) {
                    $limit -= strlen($data);
                    $stop = $limit <= 0;
                }
            }
        }
        @fclose($fp);
         
        if ('content' == $fetch_type) {
            @fclose($fp);
            return $respond_content;
        }
        //'all' == $fetch_type
        return array($respond_status, $respond_header, $respond_content);
    }
}
if (!function_exists('parse_post')) {
    function parse_post($post) {
        $post_str = '';
        if (is_array($post)) {
            foreach ($post as $attr => $val) {
                if (is_array($val)) {
                    foreach ($val as $sub_attr => $sub_val) {
                        $post_str .= sprintf("%s[%s]=%s&", urlencode($attr), urlencode($sub_attr), urlencode($sub_val));
                    }
                } else {
                    $post_str .= sprintf("%s=%s&", urlencode($attr), urlencode($val));
                }
            }
        }
         
        return $post_str ? $post_str : $post;
    }
}
if (!function_exists('parse_header')) {
    function parse_header($header, $val_callback = 'urlencode') {
        $header_str = '';
        if (is_array($header)) {
            foreach ($header as $attr => $val) {
                $header_str .= sprintf("%s: %s\r\n", $val_callback($attr), $val_callback($val));
            }
        }
     
        return $header_str ? $header_str : $header;
    }
}

2、MYsql作业: 自己封装一个 mysqli  的数据库操作类 ,能够支持多语句查询,prepare预处理,事务 ,
同时也支持正常的query,fetch操作

复制代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
class DB{
    public static function parse_stmt_bind_params($type, $params) {
        $funcArg['type'] = $type;
        $params = array_values($params);
        foreach($params as $k => $val) {
            switch ($type[$k]) {
                case 's':
                    $val = is_array($val) ? serialize($val) : (string) $val;
                    break;
                case 'i':
                    $val = (int) $val;
                    break;
                case 'd':
                    $val = (int) $val;
                    break;
                case 'b':
                    $val = (bool) $val;
                    break;
            }
            $funcArg[] = $val;
        }
        return $funcArg;
    }
    public static function prepare_sql($sql) {
        preg_match_all("#%([idsb])#i", $sql, $match);
        $prepare_type = strtolower(implode('', $match[1]));
        $sql_new = preg_replace("#%([idsb])#i", '?', $sql);
        return array($sql_new, $prepare_type);
    }
     
    public static function format($sql, $arg) {
        $count = substr_count($sql, '%');
        if (!$count) {
            return $sql;
        } elseif ($count > count($arg)) {
            $this->error('error', 'prepare', 'SQL string format error! This SQL need "' . $count . '" vars to replace into.');
        }
     
        $len = strlen($sql);
        $i = $find = 0;
        $ret = '';
        while ($i <= $len && $find < $count) {
            if ($sql{$i} == '%') {
                $next = $sql{$i + 1};
                if ($next == 's') {
                    $ret .= "'" . (is_array($arg[$find]) ? serialize($arg[$find]) : (string) $arg[$find]) . "'";
                } elseif ($next == 'f') {
                    $ret .= sprintf('%F', $arg[$find]);
                } elseif ($next == 'd') {
                    $ret .= dintval($arg[$find]);
                } elseif ($next == 'i') {
                    $ret .= $arg[$find];
                } else {
                    $ret .= "'" . ($arg[$find]) . "'";
                }
                $i++;
                $find++;
            } else {
                $ret .= $sql{$i};
            }
            $i++;
        }
        if ($i < $len) {
            $ret .= substr($sql, $i);
        }
        return $ret;
    }
    public function error($level, $func, $message='') {
        $levels = array('notice', 'waring', 'error', 'unknown');
        in_array($level, $levels) || $levels = 'unknown';
        switch ($level) {
            case 'notice':
            case 'waring':
            case 'error':
            case 'unknown':
                $return = $func . $message;
                break;
        }
     
        return $return;
    }
    public function __destruct() {
        $this->db->close();
        unset($this->db);
    }
}
class DB_mysqli extends DB{
    public $db;
    public $link;
    protected $transaction = array();
     
    public function __construct($host='127.0.0.1', $user='root', $password='root', $db_name, $port='3306') {
        $this->db = new mysqli($host, $user, $password, $db_name);
    }
    public function query($sql, $args=''){
        $data = FALSE;
        $sql = self::format($sql, $args);
        $result = $this->db->query($sql);
         
        if ($result) {
            while($row = $result->fetch_assoc()) {
                $data[] = $row;
            }
            $result->free();
        } else {
            $message = $this->db->get_warnings();
            $this->error('error', 'query', $this->db->error);
        }
         
        return $data;
    }
    public function multi_query($sql, $args=''){
        $data = '';
        $sql = self::format($sql, $args);
        if ($this->db->multi_query($sql)) {
            do {
                if ($result = $this->db->store_result()) {
                    while ( $row = $result->fetch_assoc()) {
                        $data[] = $row;
                    }
                } else {
                    $this->error('error', 'multi_query', $this->db->error);
                }
            } while ($this->db->next_result());
        }
        return $data;
    }
    public function execute_prepare($sql, $args=array(), $only_num_rows = false){
        $data = FALSE;
        list($sql, $type) = self::prepare_sql($sql);
        if (count($args) !== substr_count($sql, '?')) {
            return $this->error('error', 'prepare', 'The number of parameters does not match');
        }
        $stmt = $this->db->prepare($sql);
        if ($stmt) {
            call_user_func_array(array($stmt, "bind_param"), self::parse_stmt_bind_params($type, $args));
            $stmt->execute();
             
            if ($only_num_rows) {
                $stmt->store_result();
                $data['num_rows'] = $stmt->num_rows;
            } else {
                if ($result = $stmt->get_result()) {
                    while ( $row = $result->fetch_assoc()) {
                        $data[] = $row;
                    }
                    $result->free();
                } else {
                    $this->error('error', 'multi_query', $this->db->error);
                }
            }
             
            $stmt->close();
        }
        return $data;
    }
    public function multi_prepare($sql, $args=array(), $only_num_rows = false){
        $data = FALSE;
        list($sql, $type) = self::prepare_sql($sql);
        if (count($args) !== substr_count($sql, '?')) {
            return $this->error('error', 'prepare', 'The number of parameters does not match');
        }
        $sql_list = explode(";", $sql);
        $cut_start = 0;
        foreach ($sql_list as $k => $sub_sql) {
            $arg_num = substr_count($sub_sql, '?');
            $sub_args = array_splice($args, 0, $arg_num);
            $sub_type = substr($type, $cut_start, $arg_num);
            $cut_start += $arg_num;
             
            if ($stmt = $this->db->prepare($sub_sql)) {
                call_user_func_array(array($stmt, "bind_param"), self::parse_stmt_bind_params($sub_type, $sub_args));
                $stmt->execute();
                if ($only_num_rows) {
                    $stmt->store_result();
                    $data['num_rows'][] = $stmt->num_rows;
                } else {
                    if ($result = $stmt->get_result()) {
                        while ( $row = $result->fetch_assoc()) {
                            $data[] = $row;
                        }
                        $result->free();
                    } else {
                        $this->error('error', 'multi_query', $this->db->error);
                    }
                }
                $stmt->close();
            }
        }
     
        return $data;
    }
     
    public function transaction_start() {
        $this->db->autocommit(FALSE);
    }
    public function commit() {
        $this->db->commit();
    }
    public function rollback() {
        $this->db->rollback();
    }
     
}
$db = new DB_mysqli('127.0.0.1','root','root','test');
 
$args = array('上海市', '111', '22');
$data = $db->query("SELECT * FROM indb WHERE name=%s OR name=%s OR id=%i", $args);
var_dump($data);echo "\r\n";
 
$args = array('上海市', '111', '22','上海市', '111', '22');
$data = $db->multi_query("SELECT * FROM indb WHERE name=%s OR name=%s OR id=%i;SELECT * FROM indb WHERE name=%s OR name=%s OR id=%i", $args);
var_dump($data);echo "\r\n";
 
$args = array('上海市', '111', '22');
$data = $db->execute_prepare("SELECT * FROM indb WHERE name=%s OR name=%s OR id=%i", $args);
var_dump($data);echo "\r\n";
 
 
$args = array('上海市', '111', '22','上海市', '111', '22');
$data = $db->multi_prepare("SELECT * FROM indb WHERE name=%s OR name=%s OR id=%i;SELECT * FROM indb WHERE name=%s OR name=%s OR id=%i", $args);
var_dump($data);echo "\r\n";
 
$sql_create = "
SET FOREIGN_KEY_CHECKS=0;
 
-- ----------------------------
-- Table structure for indb_two
-- ----------------------------
DROP TABLE IF EXISTS indb_two;
CREATE TABLE indb_two (
id int(11) NOT NULL AUTO_INCREMENT,
name varchar(50) DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=35 DEFAULT CHARSET=utf8;";
 
 
 
$insert_sql="
INSERT INTO indb_two VALUES ('1', '111');
INSERT INTO indb_two VALUES ('2', '天津市');
INSERT INTO indb_two VALUES ('3', '上海市');
INSERT INTO indb_two VALUES ('4', '重庆市');
INSERT INTO indb_two VALUES ('5', '河北省');
INSERT INTO indb_two VALUES ('6', '山西省');
INSERT INTO indb_two VALUES ('7', '台湾省');
INSERT INTO indb_two VALUES ('8', '辽宁省');
INSERT INTO indb_two VALUES ('9', '吉林省');
INSERT INTO indb_two VALUES ('10', '黑龙江省');
";
$db->transaction_start();
$data = $db->query("INSERT INTO indb_two VALUES ('1', '111');");
// $data = $db->multi_query($insert_sql, '', true);
var_dump($data);echo "\r\n";
$db->rollback();
Tagged on:     

One thought on “HTTP-MYSQL

  • -0001年11月30日 at 上午12:00
    Permalink
     

     
     

    测试的时候发现,使用 事务提交的时候,前面封装的批处理sql语句的方法multi_prepare() 的放回结果弄不好,对于 select 和 insert、update 两类执行语句的返回结果处理总是想不好。

    感觉处理挺复杂的,并且没有在 mysqli API中找到比较合适的方法。

       


     

    还有一点 @jobs_lee 光明老师 提醒的 回调函数太好了,给出了一种全新的写法。call_user_func_array 总是忘记。。。还

    有一点,在过程中 在此感受到了 对于 变量 类型定义的重要。bind_param这个方法里面的参数,类型必须是对应的。还有一点php版本很气人,

    一开始使用php5.2版本,mysqli基本上用不了,各种方法都报 找不到 或是 直接跳转。建议大家以后都用 php5.3以上版本。

    nn1

发表评论