-
Notifications
You must be signed in to change notification settings - Fork 0
/
mysql.php
120 lines (87 loc) · 2.03 KB
/
mysql.php
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
<?php
namespace phpish\mysql;
function _link($link=NULL)
{
static $_link;
if (!is_null($link)) $_link = $link;
return $_link;
}
function connect($host, $username, $password, $database)
{
$link = mysqli_init();
if (!$link)
{
error_log('mysqli_init failed');
return false;
}
# TODO: Allow setting options like connection timeout: http://www.php.net/manual/en/mysqli.options.php
if (!mysqli_real_connect($link, $host, $username, $password, $database))
{
error_log('mysqli_real_connect error: (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());
return false;
}
_link($link);
return $link;
}
function query($query, $params=array(), $link=NULL)
{
$link = $link ?: _link();
$params = array_map(function($val) use($link) {
return mysqli_real_escape_string($link, $val);
}, $params);
$query = vsprintf($query, $params);
return mysqli_query($link, $query);
}
function rows($query, $params=array(), $link=NULL)
{
$rows = array();
if ($result = query($query, $params, $link))
{
while ($row = mysqli_fetch_assoc($result)) $rows[] = $row;
mysqli_free_result($result);
}
return $rows;
}
function row($query, $params=array(), $link=NULL)
{
$row = array();
if ($result = query($query, $params, $link))
{
$row = mysqli_fetch_assoc($result);
mysqli_free_result($result);
}
return $row;
}
function num_rows($result)
{
return mysqli_num_rows($result);
}
function insert()
{
# TODO: insert('table', array('field1'=>array('%s'=>$value1)))
}
function insert_id($link=NULL)
{
$link = $link ?: _link();
return mysqli_insert_id($link);
}
function update()
{
# TODO: update('table', array('field1'=>array('%s'=>$value1)), array('id'=>array('%d'=>1)))
}
function affected_rows($link=NULL)
{
$link = $link ?: _link();
return mysqli_affected_rows($link);
}
function close($link=NULL)
{
$link = $link ?: _link();
return mysqli_close($link);
}
function error($link=NUll)
{
$link = $link ?: _link();
return mysqli_error($link);
}
?>