summaryrefslogtreecommitdiff
path: root/core/classes/Database.php
blob: 35ff65f5ff0d7e28a37e6c099075444b0a33e06b (plain)
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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
<?php
/** Database Class
 * 
 */
class Database {

    /** PROPERTIES
     * -------------------------------------------------------------------------
     */

    private $throw_errors;

    private $connection = null;

    private $result = null;


    /** METHODS
     * -------------------------------------------------------------------------
     */

    /** __construct
     *
     * @param $errors: Set to true, to catch error exceptions.
     * @return void
     */
    public function __construct($errors = false)
    {
        $this->throw_errors = PRODUCTION ? false : true;

        if (null == $this->connection) {
            try {
                    $this->connection = new PDO(
                        "mysql:" . PDO_HOST . ";" . "dbname=" . DB_NAME,
                        DB_USER,
                        DB_PASS,
                        array(
                            PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'",
                            PDO::MYSQL_ATTR_LOCAL_INFILE => true
                        )
                    );

                    // handle error reporting
                    if ($this->throw_errors) {
                        $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                    }
                    $this->setTimezone();

            } catch (PDOException $exc) { handle_exception($exc); }
        }
        # return $this->connection;
    }


    /** disconnect
     * CHECK: not sure if needed
     */
    public function disconnect()
    {
        $this->connection = null;
    }


    /** set Timezone
     * (Self-explanatory)
     */
    public function setTimezone($timezone = DB_TIMEZONE) {
        // $this->connection->prepare($timezone)->execute();
    }


    /** lastInsertID
     * returns the ID of last inserted record
     */
    public function lastInsertID()
    {
        return $this->connection->insert_id;
    }


    /** query
     * ---
     * set and execute a query safely;
     * save results as associative array; DO NOT RETURN RESULTS
     * @param $sql (string): SQL query
     * @param $args (array): array of values to bind into SQL
     * @param $pypass (boolean): flag to bypass security check
     * @return $this (database handler)
     */
    public function query($sql, $args=[])
    {
        try {

            $stmt = $this->connection->prepare($sql);

            if ($args == []) {
                $result = $stmt->execute();
            
            } else {
                $result = $stmt->execute($args);
            
            }

            $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

            $this->result = $result;

            return $this;

        } catch (PDOException $exc) { handle_exception($exc); }

    }


    /** getAll
     * ---
     * return all resulted records
     * use it after db->query();
     */
    public function getAll()
    {
        return ($this->result === null) ? false : $this->result;
    }


    /** getFirst
     * ---
     * get first row of the resulted query;
     * used when one row is expected
     * ex. $db->query('SELECT * FROM users WHERE id = :id',['id'=>1])->getFirst();
     */
    public function getFirst()
    {
        if (($this->result === null) || ($this->result == [])) {
            return false;

        } else { return $this->result[0]; }
    }


    /** getOnly
     * ---
     * return the first column value of the first row
     * used when only one value is needed
     * ex. $db->query('SELECT Count(id) FROM table',[])->getOnly();
     */
    public function getOnly()
    {
        if (($this->result === null) || ($this->result == [])) {
            return false;
        
        } else { return array_values($this->result[0])[0]; }
    }


    /** runQuery
     * --- (shortcut method)
     * execute a query safely;
     * return results as associative array
     * @param $sql (string): SQL query
     * @param $args (array): array of values to bind into SQL
     * @param $pypass (boolean): flag to bypass security check
     */
    public function runQuery($sql, $args=[])
    {
        return $this->query($sql, $args)->getAll();
    }


    /** runLimitQuery( sql, args, limit=100, offset = null )
     * set LIMIT / OFFSET clauses in a secure way
     * @param $sql (string): SQL query
     * @param $args (array): array of values to bind into SQL
     * @param $limit  (int): LIMIT number
     * @param $offset (int): OFFSET number
     */
    public function runLimitQuery($sql, $args, $limit = 100, $offset = null)
    {
        $limitStr = $offsetStr = "";

        // construct LIMIT clause
        if (is_int($limit)) {
            $limitStr = " LIMIT {$limit}";

            // construct OFFSET clause (when a LIMIT pre-exists)
            if (is_int($offset)) {
                $offsetStr =" OFFSET {$offset}";
            }
        }

        $sql = $sql . $limitStr . $offsetStr;

        return $this->runQuery($sql, $args);
    }


    /** insert
     * @param $table (string): name of table
     * @param $values: an associative of (fieldName => value) pairs
     * 
     * example call:
     * ---
     * $db->insert('products',
     *    [
     *      'title' => 'My Dark Chocolate 200g',
     *      'text' => 'Lorem ipsum dolor sit amet, consectetur adipiscing elit ...',
     *      'isFood' => 1,
     *      'isToxic' => 0 
     *    ]
     * );
     * 
     * ...which prepares the SQL query:
     * INSERT INTO products (title, text, isFood, isToxic)
     * VALUES (:title, :text, :isFood, :isToxic)
     * 
     * ...and injects the values: [ :title => 'My Dark Chocolate 200g' , ... ]
     */
    public function insert($table, array $values)
    {
        $fieldSets = [];
        $valueSets = [];
        $bindSets = [];

        foreach($values as $key => $val) {
            $fieldSets[] = $key; 
            $valueSets[] =':'. $key;
            $bindSets[':'. $key] = $val;
        }

        $sql = "INSERT INTO {$table} (". implode(', ', $fieldSets) .") 
                VALUES (". implode(', ', $valueSets) .")";
        
        return $this->runQuery($sql, $bindSets);
    }


    /** update
     * @param $table (string): name of table
     * @param $values: an associative of (fieldName => value) pairs
     * @param $id: an associative of (fieldName => value) index fields
     * 
     * example call:
     * ---
     * $db->update('products',
     *    [ 'title' => 'My Chocolate','isFood' => 1 ],
     *    [ 'id' => 123 ]
     * );
     * 
     * ...which prepares the SQL query:
     * UPDATE products SET `title` = :title, `isFood` = :isFood WHERE id = :id
     * 
     * ...and injects: [':title'=> 'My Chocolate' , ':isFood'=> 1 , ':id'=> 123]
     */
    public function update( $table, array $values, array $identity)
    {   
        $fieldSets = [];    // array of field names
        $idSets = [];       // array of data-holders
        $bindSets = [];     // array of data-bindings

        foreach($values as $key => $val) {
            $fieldSets[] = "{$key} = :{$key}";
            $bindSets[':'. $key] = $val;
        }

        foreach($identity as $key => $val) {
            $idSets = "{$key} = :{$key}";
            $bindSets[':'. $key] = $val;
        }

        $sql = "UPDATE {$table} SET ". implode(', ', $fieldSets)
                ." WHERE ". implode(" AND ", $idSets);

        return $this->runQuery($sql, $bindsArray);
    }

    
    /** multiInsert( table, fields , values )
     * Construct a multiple-insert clause
     * 
     * @param $table (string): name of table
     * @param $fields (array): array with field-names
     * @param $values (array): array of value-arrays 
     *
     * example call:
     * ---
     * $db->multiInsert('order_products',
     *  [ 'orderID', 'productID', 'unitPrice', 'quantity', 'note' ],
     *  [
     *      [ 124, 102030, 1.25, 5, '' ],
     *      [ 124, 102040, 10.50, 2, 'some note about product #102040' ],
     *      [ 124, 102050, 7.20, 3, '' ],
     *      [ 124, 102060, 3.25, 1, 'some other note' ]
     *  ]
     * );
     */   
    public function multiInsert($table, array $fieldsArray, array $valuesArray)
    {
        if (count($fieldsArray) != count($valuesArray[0])) {
            throw new Exception('Fields and value arrays don\'t match.');
        }

        // setup fieldsSet 
        // ex. "(Title, Price, Status)"
        $fieldsSet = ' (`'. implode(
            '`, `',     // make sure fieldnames are not SQL-bound terms
            str_replace('`', '', $fieldsArray)      // clean fieldnames
        ) .'`) ';

        // setup holders array and bind-values array
        // ex. "(:Title1, :Price1, :Status1), (:Title2, :Price2, :Status2), ...",
        $holdersArray = [];
        $bindsArray = [];
        $counter = 1;
        foreach($valuesArray as $key => $rowArray) {
            $rowHolders = [];

            foreach($itemArray as $key => $val) {
                $rowHolders = ':'. $fieldsArray[$key] . $counter;
                $bindsArray[ ':'. $fieldsArray[$key] . $counter ] = $val;
            }
            $holdersArray[] = '('. implode(', ', $rowHolders ) .')';
            $counter++;
        }

        $sql = "INSERT INTO {$table}" . $fieldsSet
            . ' VALUES '. impload(', ', $holdersArray);

        return $this->runQuery($sql, $bindsArray);
    }

}