Completed
Push — master ( 4076e7...56163a )
by Daniel
02:39
created

getMySQLqueryWithParameterIdentifier()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 0 Features 0
Metric Value
c 4
b 0
f 0
dl 0
loc 8
rs 9.4285
cc 2
eloc 5
nc 2
nop 2
1
<?php
2
3
/**
4
 *
5
 * The MIT License (MIT)
6
 *
7
 * Copyright (c) 2015 Daniel Popiniuc
8
 *
9
 * Permission is hereby granted, free of charge, to any person obtaining a copy
10
 * of this software and associated documentation files (the "Software"), to deal
11
 * in the Software without restriction, including without limitation the rights
12
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13
 * copies of the Software, and to permit persons to whom the Software is
14
 * furnished to do so, subject to the following conditions:
15
 *
16
 * The above copyright notice and this permission notice shall be included in all
17
 * copies or substantial portions of the Software.
18
 *
19
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25
 * SOFTWARE.
26
 *
27
 */
28
29
namespace danielgp\common_lib;
30
31
/**
32
 * Usefull functions to get quick MySQL content
33
 *
34
 * @author Daniel Popiniuc
35
 */
36
trait MySQLiByDanielGP
37
{
38
39
    use MySQLiByDanielGPnumbers,
40
        MySQLiMultipleExecution;
41
42
    /**
43
     * Intiates connection to MySQL
44
     *
45
     * @param array $mySQLconfig
46
     *
47
     * $mySQLconfig           = [
48
     * 'host'     => MYSQL_HOST,
49
     * 'port'     => MYSQL_PORT,
50
     * 'username' => MYSQL_USERNAME,
51
     * 'password' => MYSQL_PASSWORD,
52
     * 'database' => MYSQL_DATABASE,
53
     * ];
54
     */
55
    protected function connectToMySql($mySQLconfig)
56
    {
57
        if (is_null($this->mySQLconnection)) {
58
            extract($mySQLconfig);
59
            $this->mySQLconnection = new \mysqli($host, $username, $password, $database, $port);
60
            if (is_null($this->mySQLconnection->connect_error)) {
61
                return '';
62
            }
63
            $this->mySQLconnection = null;
64
            $erNo                  = $this->mySQLconnection->connect_errno;
65
            $erMsg                 = $this->mySQLconnection->connect_error;
66
            $msg                   = $this->lclMsgCmn('i18n_Feedback_ConnectionError');
67
            return sprintf($msg, $erNo, $erMsg, $host, $port, $username, $database);
68
        }
69
    }
70
71
    /**
72
     * Returns a Date field 2 use in a form
73
     *
74
     * @param array $value
75
     * @return string
76
     */
77
    protected function getFieldOutputDate($value)
78
    {
79
        $defaultValue = $this->getFieldValue($value);
80
        if (is_null($defaultValue)) {
81
            $defaultValue = date('Y-m-d');
82
        }
83
        $inA = [
84
            'type'      => 'text',
85
            'name'      => $value['Field'],
86
            'id'        => $value['Field'],
87
            'value'     => $defaultValue,
88
            'size'      => 10,
89
            'maxlength' => 10,
90
            'onfocus'   => implode('', [
91
                'javascript:NewCssCal(\'' . $value['Field'],
92
                '\',\'yyyyMMdd\',\'dropdown\',false,\'24\',false);',
93
            ]),
94
        ];
95
        return $this->setStringIntoShortTag('input', $inA) . $this->setCalendarControl($value['Field']);
96
    }
97
98
    /**
99
     * Returns a Time field 2 use in a form
100
     *
101
     * @param array $value
102
     * @param array $iar
103
     * @return string
104
     */
105
    protected function getFieldOutputTime($value, $iar = [])
106
    {
107
        return $this->getFieldOutputTT($value, 8, $iar);
108
    }
109
110
    /**
111
     * Provides a detection if given Query does contain a Parameter
112
     * that may require statement processing later on
113
     *
114
     * @param string $sQuery
115
     * @param string $paramIdentifier
116
     * @return boolean
117
     */
118
    protected function getMySQLqueryWithParameterIdentifier($sQuery, $paramIdentifier)
119
    {
120
        $sReturn = true;
121
        if (strpos($sQuery, $paramIdentifier) === false) {
122
            $sReturn = false;
123
        }
124
        return $sReturn;
125
    }
126
127
    /**
128
     * Transmit Query to MySQL server and get results back
129
     *
130
     * @param string $sQuery
131
     * @param string $sReturnType
132
     * @param array $ftrs
133
     * @return boolean|array|string
134
     */
135
    protected function setMySQLquery2Server($sQuery, $sReturnType = null, $ftrs = null)
136
    {
137
        if (is_null($sReturnType)) {
138
            $this->mySQLconnection->query(html_entity_decode($sQuery));
139
            return '';
140
        } elseif (is_null($this->mySQLconnection)) {
141
            return ['customError' => $this->lclMsgCmn('i18n_MySQL_ConnectionNotExisting'), 'result' => null];
142
        }
143
        $result = $this->mySQLconnection->query(html_entity_decode($sQuery));
144
        if ($result) {
145
            return $this->setMySQLquery2ServerConnected(['Result' => $result, 'RType' => $sReturnType, 'F' => $ftrs]);
146
        }
147
        $erM  = [$this->mySQLconnection->errno, $this->mySQLconnection->error];
148
        $cErr = sprintf($this->lclMsgCmn('i18n_MySQL_QueryError'), $erM[0], $erM[1]);
149
        return ['customError' => $cErr, 'result' => null];
150
    }
151
152
    /**
153
     * Turns a raw query result into various structures
154
     * based on different predefined $parameters['returnType'] value
155
     *
156
     * @param array $parameters
157
     * @return array as ['customError' => '...', 'result' => '...']
158
     */
159
    private function setMySQLquery2ServerByPattern($parameters)
160
    {
161
        $aReturn = $parameters['return'];
162
        $vld     = $this->setMySQLqueryValidateInputs($parameters);
163
        if ($vld[1] !== '') {
164
            return ['customError' => $vld[1], 'result' => ''];
165
        } elseif ($parameters['returnType'] == 'value') {
166
            return ['customError' => $vld[1], 'result' => $parameters['QueryResult']->fetch_row()[0]];
167
        }
168
        $counter2 = 0;
169
        for ($counter = 0; $counter < $parameters['NoOfRows']; $counter++) {
170
            $line = $parameters['QueryResult']->fetch_row();
171
            $this->setMySQLquery2ServerByPatternLine($parameters, $line, $counter, $counter2, $aReturn);
172
            $counter2++;
173
        }
174
        return ['customError' => '', 'result' => $aReturn['result']];
175
    }
176
177
    private function setMySQLquery2ServerByPatternKey($parameters, $line, $counter)
178
    {
179
        switch ($parameters['returnType']) {
180
            case 'array_key_value':
181
                return [$line[0], $line[1]];
182
            // intentionally left open
183
            case 'array_key2_value':
184
                return [$line[0] . '@' . $line[1], $line[1]];
185
            // intentionally left open
186
            case 'array_numbered':
187
                return [$counter, $line[0]];
188
            // intentionally left open
189
        }
190
    }
191
192
    private function setMySQLquery2ServerByPatternLine($parameters, $line, $counter, $counter2, &$aReturn)
193
    {
194
        if (in_array($parameters['returnType'], ['array_key_value', 'array_key2_value', 'array_numbered'])) {
195
            $rslt                        = $this->setMySQLquery2ServerByPatternKey($parameters, $line, $counter);
196
            $aReturn['result'][$rslt[0]] = $rslt[1];
197
        } elseif ($parameters['returnType'] == 'array_key_value2') {
198
            $aReturn['result'][$line[0]][] = $line[1];
199
        } else {
200
            $finfo = $parameters['QueryResult']->fetch_fields();
201
            $this->setMySQLquery2ServerByPatternLineAdvanced($parameters, $finfo, $line, $counter2, $aReturn);
202
        }
203
    }
204
205
    private function setMySQLquery2ServerByPatternLineAdvanced($parameters, $finfo, $line, $counter2, &$aReturn)
206
    {
207
        foreach ($finfo as $columnCounter => $value) {
208
            switch ($parameters['returnType']) {
209
                case 'array_first_key_rest_values':
210
                    if ($columnCounter !== 0) {
211
                        $aReturn['result'][$line[0]][$value->name] = $line[$columnCounter];
212
                    }
213
                    break;
214
                case 'array_pairs_key_value':
215
                    $aReturn['result'][$value->name]                                   = $line[$columnCounter];
216
                    break;
217
                case 'full_array_key_numbered':
218
                    $aReturn['result'][$counter2][$value->name]                        = $line[$columnCounter];
219
                    break;
220
                case 'full_array_key_numbered_with_record_number_prefix':
221
                    $parameters['prefix']                                              = 'RecordNo';
222
                // intentionally left open
223
                case 'full_array_key_numbered_with_prefix':
224
                    $aReturn['result'][$parameters['prefix']][$counter2][$value->name] = $line[$columnCounter];
225
                    break;
226
            }
227
        }
228
    }
229
230
    private function setMySQLquery2ServerConnected($inArray)
231
    {
232
        if ($inArray['RType'] == 'id') {
233
            return ['customError' => '', 'result' => $this->mySQLconnection->insert_id];
234
        } elseif ($inArray['RType'] == 'lines') {
235
            return ['result' => $inArray['Result']->num_rows, 'customError' => ''];
236
        }
237
        $parameters = [
238
            'NoOfColumns' => $inArray['Result']->field_count,
239
            'NoOfRows'    => $inArray['Result']->num_rows,
240
            'QueryResult' => $inArray['Result'],
241
            'returnType'  => $inArray['RType'],
242
            'return'      => ['customError' => '', 'result' => null]
243
        ];
244
        if (substr($inArray['RType'], -6) == 'prefix') {
245
            $parameters['prefix'] = $inArray['F']['prefix'];
246
        }
247
        return $this->setMySQLquery2ServerByPattern($parameters);
248
    }
249
}
250