1+ <?php
2+
3+ /**
4+ * Class EasySQL provides an easy-to-use interface for basic MySQL database operations.
5+ */
6+ class EasySQL
7+ {
8+ /** @var string $host the database host */
9+ private $ host ;
10+
11+ /** @var string $username the database username */
12+ private $ username ;
13+
14+ /** @var string $password the database password */
15+ private $ password ;
16+
17+ /** @var string $database the database name */
18+ private $ database ;
19+
20+ /** @var string $charset the database charset */
21+ private $ charset ;
22+
23+ /** @var PDO $pdo the PDO object for database access */
24+ private $ pdo ;
25+
26+ /**
27+ * Constructs a new EasySQL instance with the given database connection parameters.
28+ *
29+ * @param string $host the database host
30+ * @param string $database the database name
31+ * @param string $username the database username
32+ * @param string $password the database password
33+ * @param string $charset the database charset (default: utf8)
34+ *
35+ * @throws \PDOException if the connection to the database fails
36+ */
37+ public function __construct ($ host , $ database , $ username , $ password , $ charset = 'utf8 ' )
38+ {
39+ $ this ->host = $ host ;
40+ $ this ->username = $ username ;
41+ $ this ->password = $ password ;
42+ $ this ->database = $ database ;
43+ $ this ->charset = $ charset ;
44+
45+ // Set up the PDO object with the given parameters
46+ $ dsn = "mysql:host= $ this ->host ;dbname= $ this ->database ;charset= $ this ->charset " ;
47+ $ options = array (
48+ PDO ::ATTR_ERRMODE => PDO ::ERRMODE_EXCEPTION ,
49+ PDO ::ATTR_DEFAULT_FETCH_MODE => PDO ::FETCH_ASSOC ,
50+ PDO ::ATTR_EMULATE_PREPARES => false ,
51+ );
52+ try {
53+ $ this ->pdo = new PDO ($ dsn , $ this ->username , $ this ->password , $ options );
54+ } catch (\PDOException $ e ) {
55+ throw new \PDOException ($ e ->getMessage (), (int ) $ e ->getCode ());
56+ }
57+ }
58+
59+ /**
60+ * Inserts a new row into the specified table with the given data.
61+ *
62+ * @param string $table the name of the table
63+ * @param array $data an associative array of column names and values
64+ *
65+ * @return bool true if the insert was successful, false otherwise
66+ */
67+ public function insert ($ table , $ data )
68+ {
69+ $ columns = implode (', ' , array_keys ($ data ));
70+ $ placeholders = implode (', ' , array_fill (0 , count ($ data ), '? ' ));
71+ $ values = array_values ($ data );
72+ $ sql = "INSERT INTO $ table ( $ columns) VALUES ( $ placeholders) " ;
73+ $ stmt = $ this ->pdo ->prepare ($ sql );
74+ return $ stmt ->execute ($ values );
75+ }
76+
77+ /**
78+ * Retrieves rows from the specified table that match the specified criteria.
79+ *
80+ * @param string $table the name of the table
81+ * @param string|array $columns the names of the columns to retrieve (default: *)
82+ * @param array $conditions an associative array of conditions for the query (default: array())
83+ * @param array $options an associative array of options for the query (default: array())
84+ *
85+ * @return array an array of rows that match the query criteria
86+ */
87+ public function select ($ table , $ columns = '* ' , $ conditions = array (), $ options = array ())
88+ {
89+ $ sql = "SELECT $ columns FROM $ table " ;
90+ $ where = '' ;
91+ $ bindings = array ();
92+ if (!empty ($ conditions )) {
93+ $ whereArray = array ();
94+ foreach ($ conditions as $ column => $ value ) {
95+ if (is_array ($ value )) {
96+ $ operator = key ($ value );
97+ if ($ operator === 'LIKE ' ) {
98+ $ value = "% {$ value [$ operator ]}% " ;
99+ }
100+ $ whereArray [] = "$ column $ operator ? " ;
101+ $ bindings [] = $ value ;
102+ } else {
103+ $ whereArray [] = "$ column = ? " ;
104+ $ bindings [] = $ value ;
105+ }
106+ }
107+ $ where = 'WHERE ' . implode (' AND ' , $ whereArray );
108+ }
109+ $ sql .= " $ where " ;
110+ if (!empty ($ options )) {
111+ foreach ($ options as $ option => $ value ) {
112+ $ sql .= " $ option $ value " ;
113+ }
114+ }
115+ $ stmt = $ this ->pdo ->prepare ($ sql );
116+ $ stmt ->execute ($ bindings );
117+ return $ stmt ->fetchAll ();
118+ }
119+
120+ /**
121+ * Updates rows in the specified table that match the specified criteria with the given data.
122+ *
123+ * @param string $table the name of the table
124+ * @param array $data an associative array of column names and new values
125+ * @param string $where the WHERE clause for the query (default: '')
126+ * @param array $bindings an array of values to bind to the placeholders in the WHERE clause (default: array())
127+ *
128+ * @return bool true if the update was successful, false otherwise
129+ */
130+ public function update ($ table , $ data , $ where = '' , $ bindings = array ())
131+ {
132+ $ set = array ();
133+ foreach ($ data as $ column => $ value ) {
134+ $ set [] = "$ column = ? " ;
135+ }
136+ $ set = implode (', ' , $ set );
137+ $ sql = "UPDATE $ table SET $ set " ;
138+ if (!empty ($ where )) {
139+ $ sql .= " WHERE $ where " ;
140+ }
141+ $ values = array_values ($ data );
142+ $ stmt = $ this ->pdo ->prepare ($ sql );
143+ $ values = array_merge ($ values , $ bindings );
144+ return $ stmt ->execute ($ values );
145+ }
146+
147+ /**
148+ * Delete rows from a table.
149+ *
150+ * @param string $table The name of the table to delete rows from.
151+ * @param string $where The WHERE clause for the delete statement.
152+ * @param array $bindings An array of parameter values to bind to the SQL statement.
153+ *
154+ * @return bool Whether the delete statement was successful.
155+ */
156+ public function delete ($ table , $ where = '' , $ bindings = array ())
157+ {
158+ $ sql = "DELETE FROM $ table " ;
159+ if (!empty ($ where )) {
160+ $ sql .= " WHERE $ where " ;
161+ }
162+ $ stmt = $ this ->pdo ->prepare ($ sql );
163+ return $ stmt ->execute ($ bindings );
164+ }
165+
166+ /**
167+ * Get the number of rows in a table.
168+ *
169+ * @param string $table The name of the table to count rows in.
170+ * @param string $where The WHERE clause for the count statement.
171+ * @param array $bindings An array of parameter values to bind to the SQL statement.
172+ *
173+ * @return int The number of rows in the table.
174+ */
175+ public function count ($ table , $ where = '' , $ bindings = array ())
176+ {
177+ $ sql = "SELECT COUNT(*) FROM $ table " ;
178+ if (!empty ($ where )) {
179+ $ sql .= " WHERE $ where " ;
180+ }
181+ $ stmt = $ this ->pdo ->prepare ($ sql );
182+ $ stmt ->execute ($ bindings );
183+ return $ stmt ->fetchColumn ();
184+ }
185+
186+ /**
187+ * Get the sum of a column in a table.
188+ *
189+ * @param string $table The name of the table to sum the column in.
190+ * @param string $column The name of the column to sum.
191+ * @param string $where The WHERE clause for the sum statement.
192+ * @param array $bindings An array of parameter values to bind to the SQL statement.
193+ *
194+ * @return int The sum of the column in the table.
195+ */
196+ public function sum ($ table , $ column , $ where = '' , $ bindings = array ())
197+ {
198+ $ sql = "SELECT SUM( $ column) FROM $ table " ;
199+ if (!empty ($ where )) {
200+ $ sql .= " WHERE $ where " ;
201+ }
202+ $ stmt = $ this ->pdo ->prepare ($ sql );
203+ $ stmt ->execute ($ bindings );
204+ return $ stmt ->fetchColumn ();
205+ }
206+
207+ /**
208+ * Calculates the average of a column in a table.
209+ *
210+ * @param string $table The name of the table to select from.
211+ * @param string $column The name of the column to calculate the average of.
212+ * @param string $where Optional WHERE clause to filter results.
213+ * @param array $bindings Optional parameter bindings for the WHERE clause.
214+ *
215+ * @return mixed The average of the column as a float, or FALSE on failure.
216+ */
217+ public function avg ($ table , $ column , $ where = '' , $ bindings = array ())
218+ {
219+ $ sql = "SELECT AVG( $ column) FROM $ table " ;
220+ if (!empty ($ where )) {
221+ $ sql .= " WHERE $ where " ;
222+ }
223+ $ stmt = $ this ->pdo ->prepare ($ sql );
224+ $ stmt ->execute ($ bindings );
225+ return $ stmt ->fetchColumn ();
226+ }
227+
228+ /**
229+ * Finds the minimum value of a column in a table.
230+ *
231+ * @param string $table The name of the table to select from.
232+ * @param string $column The name of the column to find the minimum of.
233+ * @param string $where Optional WHERE clause to filter results.
234+ * @param array $bindings Optional parameter bindings for the WHERE clause.
235+ *
236+ * @return mixed The minimum value of the column, or FALSE on failure.
237+ */
238+ public function min ($ table , $ column , $ where = '' , $ bindings = array ())
239+ {
240+ $ sql = "SELECT MIN( $ column) FROM $ table " ;
241+ if (!empty ($ where )) {
242+ $ sql .= " WHERE $ where " ;
243+ }
244+ $ stmt = $ this ->pdo ->prepare ($ sql );
245+ $ stmt ->execute ($ bindings );
246+ return $ stmt ->fetchColumn ();
247+ }
248+
249+ /**
250+ * Finds the maximum value of a column in a table.
251+ *
252+ * @param string $table The name of the table to select from.
253+ * @param string $column The name of the column to find the maximum of.
254+ * @param string $where Optional WHERE clause to filter results.
255+ * @param array $bindings Optional parameter bindings for the WHERE clause.
256+ *
257+ * @return mixed The maximum value of the column, or FALSE on failure.
258+ */
259+ public function max ($ table , $ column , $ where = '' , $ bindings = array ())
260+ {
261+ $ sql = "SELECT MAX( $ column) FROM $ table " ;
262+ if (!empty ($ where )) {
263+ $ sql .= " WHERE $ where " ;
264+ }
265+ $ stmt = $ this ->pdo ->prepare ($ sql );
266+ $ stmt ->execute ($ bindings );
267+ return $ stmt ->fetchColumn ();
268+ }
269+
270+ /**
271+ * Runs a SQL query and returns the results.
272+ *
273+ * @param string $sql The SQL query to run.
274+ * @param array $bindings Optional parameter bindings for the SQL query.
275+ *
276+ * @return array An array of results from the SQL query.
277+ */
278+ public function query ($ sql , $ bindings = array ())
279+ {
280+ $ stmt = $ this ->pdo ->prepare ($ sql );
281+ $ stmt ->execute ($ bindings );
282+ return $ stmt ->fetchAll ();
283+ }
284+
285+ /**
286+ * Retrieves a row from a table by ID.
287+ *
288+ * @param string $table The name of the table to select from.
289+ * @param int $id The ID of the row to select.
290+ *
291+ * @return array The row from the table with the specified ID.
292+ */
293+ public function get ($ table , $ id )
294+ {
295+ $ sql = "SELECT * FROM $ table WHERE id = ? " ;
296+ $ stmt = $ this ->pdo ->prepare ($ sql );
297+ $ stmt ->execute (array ($ id ));
298+ return $ stmt ->fetch ();
299+ }
300+
301+ /**
302+ * Retrieves a row from a table by ID using a custom SQL query.
303+ *
304+ * @param string $table The name of the table to select from.
305+ * @param int $id The ID of the row to select.
306+ * @param string $columns The columns to select from the table.
307+ *
308+ * @return array The row from the table with the specified ID.
309+ *
310+ * @throws \Exception If the query file cannot be found.
311+ */
312+ public function find ($ table , $ id , $ columns = '* ' )
313+ {
314+ $ sql_file = "SELECT_BY_ID_ $ table.sql " ;
315+ if (file_exists ($ sql_file )) {
316+ $ sql = file_get_contents ($ sql_file );
317+ $ stmt = $ this ->pdo ->prepare ($ sql );
318+ $ stmt ->execute (array ($ id ));
319+ return $ stmt ->fetch ();
320+ } else {
321+ throw new \Exception ("Cannot find query file: $ sql_file " );
322+ }
323+ }
324+
325+ /**
326+ * Retrieves multiple rows from a table.
327+ *
328+ * @param string $table The name of the table to select from.
329+ * @param string $columns The columns to select from the table.
330+ * @param string $where The WHERE clause of the SQL query.
331+ * @param array $bindings Optional parameter bindings for the SQL query.
332+ *
333+ * @return array An array of rows from the table that match the WHERE clause.
334+ */
335+ public function findAll ($ table , $ columns = '* ' , $ where = '' , $ bindings = array ())
336+ {
337+ $ sql = "SELECT $ columns FROM $ table " ;
338+ if (!empty ($ where )) {
339+ $ sql .= " WHERE $ where " ;
340+ }
341+ $ stmt = $ this ->pdo ->prepare ($ sql );
342+ $ stmt ->execute ($ bindings );
343+ return $ stmt ->fetchAll ();
344+ }
345+
346+ /**
347+ * Saves data to a table, either by updating an existing row or creating a new one.
348+ *
349+ * @param string $table The name of the table to save to.
350+ * @param array $data An associative array of column names and values to save.
351+ *
352+ * @return bool True if the save was successful, false otherwise.
353+ */
354+ public function save ($ table , $ data )
355+ {
356+ if (isset ($ data ['id ' ])) {
357+ $ set = array ();
358+ foreach ($ data as $ column => $ value ) {
359+ if ($ column !== 'id ' ) {
360+ $ set [] = "$ column = ? " ;
361+ }
362+ }
363+ $ set = implode (', ' , $ set );
364+ $ sql = "UPDATE $ table SET $ set WHERE id = ? " ;
365+ $ values = array_values ($ data );
366+ $ stmt = $ this ->pdo ->prepare ($ sql );
367+ return $ stmt ->execute (array_merge ($ values , array ($ data ['id ' ])));
368+ } else {
369+ $ columns = implode (', ' , array_keys ($ data ));
370+ $ placeholders = implode (', ' , array_fill (0 , count ($ data ), '? ' ));
371+ $ values = array_values ($ data );
372+ $ sql = "INSERT INTO $ table ( $ columns) VALUES ( $ placeholders) " ;
373+ $ stmt = $ this ->pdo ->prepare ($ sql );
374+ return $ stmt ->execute ($ values );
375+ }
376+ }
377+
378+ /**
379+ * Sets the character set for the database connection.
380+ *
381+ * @param string $charset The character set to use.
382+ */
383+ public function setCharset ($ charset )
384+ {
385+ $ this ->charset = $ charset ;
386+ $ dsn = "mysql:host= $ this ->host ;dbname= $ this ->database ;charset= $ this ->charset " ;
387+ $ this ->pdo = new PDO ($ dsn , $ this ->username , $ this ->password );
388+ }
389+ }
0 commit comments