phpmysql

phpmysql~

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

<?php

class DB{
public $host;
public $attr;
public $username;
public $password;
public $dbname;
public $link;

public function __construct($config) {
isset($config['attr']) ? $this->attr = $config['attr'] : 'localhost';
isset($config['host']) ? $this->host = $config['host'] : '3306';
isset($config['username']) ? $this->username = $config['username'] : 'root';
isset($config['password']) ? $this->password = $config['password'] : 'root';
isset($config['dbname']) ? $this->dbname = $config['dbname'] : 'jianshu';

$this->connect();
$this->setcharset('utf8');
}

public function connect()
{
$this->link = mysqli_connect($this->attr.':'.$this->host,$this->username,$this->password,$this->dbname);
}

public function query($sql)
{
if(!$result = mysqli_query($this->link,$sql)) {
echo myssqli_error();
echo myssqli_errno();
} else {
return $result;
}
}
public function setCharset($charset)
{
mysqli_set_charset($this->link,$charset);
}
public function fetchAssoc($sql)
{
$result = $this->query($sql);
$arr = array();
while($row = mysqli_fetch_assoc($result))
{
printf("%s : %s \n",$row["id"],$row["name"]);
}
}
public function fetchAssocOrNum($sql,$type)
{
ini_set("display_errors","off");
$result = $this->query($sql);

if(!in_array($type,array('assoc','row'))) {
die('mysqli error!');
}

$fucname = mysqli_fetch."_".$type;

$selectIndex = strripos(func_get_args()[0],'select');
$fromIndex = strripos(func_get_args()[0],'from');
$selectStr = substr(func_get_args()[0],strlen('select') + 1,$fromIndex - strlen('select'));
$selectArr = explode(",",$selectStr);
$selectArrLen = count($selectArr);

switch($type) {
case 'assoc':
while($res = $fucname($result)) {
foreach($selectArr as $k) {
printf("%s = %s \n",$k,$res[$k]);
}
}
case 'row':
$num = 0;
while($res = $fucname($result)) {
for($i = 0; $i<$selectArrLen; $i++) {
printf("%d = %s",$i,$res[$i]);
}
}
}
}

}

$db = new DB([
'attr' => '127.0.0.1',
'host' => '3306',
'username' => 'root',
'password' => 'root',
'dbname' => 'jianshu'
]);

$db->setCharset('utf8');

$db->fetchAssocOrNum('select author,title from contents','assoc');

?>

文章目录
,
//