2024.8.23
Loading...
Searching...
No Matches
db_common.inc.php
Go to the documentation of this file.
1<?php
2
3/**
4* WINBINDER - The native Windows binding for PHP for PHP
5*
6* Copyright � Hypervisual - see LICENSE.TXT for details
7* Authors: Rubem Pechansky and Hans Rebel
8*
9* Database wrapper functions for WinBinder
10* version 2b tested with SQLite and mySQL 7.mar
11*/
12// ------------------------------------------------------------ DATABASE-SPECIFIC
13// You may define APPPREFIX and DB_DATABASE in the application
14// APPPREFIX can be used to separate applications within one database
15// allowed chars are A_Z,a-z,_ ( e.g.: "myAPP_" )
16// for direct SQL use raw_db_query, keep in mind to handle APPPREFIX in your SQL
17// for tablenames and possible prefixes to fieldnames in returned records
18define("DB_WRAPVERSION", "db_v2b");
19
20if (!defined("APPPREFIX")) define("APPPREFIX", "");
21if (!defined("DB_DATABASE")) define("DB_DATABASE", "SQLite");
22
23$_mainpath = pathinfo(__FILE__);
24$_mainpath = $_mainpath["dirname"] . "/";
25
26include $_mainpath . "db_" . strtolower(DB_DATABASE) . ".inc.php";
27
28/**
29* db_get_info()
30* Returns database and wrapper version information
31*
32* @param string $what
33* @return string
34*/
35function db_get_info($info = "")
36{
37 switch (strtolower($info)) {
38 case "version":
39 return DB_DATABASE . " " . raw_get_db_version() . " with Database Wrapper " . DB_WRAPVERSION;
40
41 case "dbtype":
42 return DB_DATABASE;
43
44 case "dbversion":
45 return raw_get_db_version();
46
47 case "wrapversion":
48 return DB_WRAPVERSION;
49 }
50}
51// -----------------------wrapper for APPPREFIX----- DATABASE FUNCTIONS
52/**
53* db_open_database()
54* Opens and connects an existing database.
55*
56* @param $database
57* @param string $server
58* @param string $username
59* @param string $password
60* @return resource or "FALSE"
61*/
62function db_open_database($database, $server = "", $username = "", $password = "")
63{
64 return raw_db_open_database($database, $server, $username , $password);
65}
66
67/**
68* db_create_database()
69* Creates a database if it does not exist
70*
71* @param $database
72* @param string $server
73* @param string $username
74* @param string $password
75* @return resource or "FALSE"
76*/
77function db_create_database($database, $server = "", $username = "", $password = "")
78{
79 return raw_db_create_database($database, $server, $username , $password);
80}
81
82/**
83* db_list_database_tables()
84* Returns an array with the list of tables of the current database
85*
86* @return result or "FALSE"
87*/
89{
91 if (!$tables) {
92 return false;
93 }
94 $tmp_tabs = "";
95 $prefixlen = strlen(trim(APPPREFIX));
96 if ($prefixlen > 0) {
97 foreach($tables as $table) {
98 if (!(stristr(substr($table, 0, $prefixlen), APPPREFIX) === false)) {
99 $tmp_tabs[] = substr($table, strlen(APPPREFIX));
100 }
101 }
102 if ($tmp_tabs == "") {
103 return false;
104 }
105 return $tmp_tabs;
106 } else return $tables;
107}
108/**
109* db_close_database()
110*
111* @return bool "TRUE" or "FALSE"
112*/
114{
115 return raw_db_close_database();
116}
117// -------------------------------------------------------------- TABLE FUNCTIONS
118/**
119* db_table_exists()
120*
121* @param $tablename of an opened database
122* @return bool "TRUE" if table $tablename exists in the current database
123*/
124function db_table_exists($tablename)
125{
126 global $g_lasttable;
127
128 if (!$tablename)
129 $tablename = $g_lasttable;
130 $g_lasttable = $tablename;
131 return raw_db_table_exists(APPPREFIX . $tablename);
132}
133
134/**
135* db_create_table()
136*
137* @param $tablename
138* @param $fieldnames ( beside "id" )
139* @param $fieldattrib
140* @param string $idfield ( set to "id" )
141* @param array $valarray ( $valarray[0] = 1.record, $valarray[1] = 2.record, ... )
142* @return bool "TRUE" or "FALSE" if Table already exists, could not create Table, could not create Records
143*/
144function db_create_table($tablename, $fieldnames, $fieldattrib, $idfield = "id", $valarray = null)
145{
146 global $g_lasttable;
147
148 if ($tablename == null || $tablename == "")
149 $tablename = $g_lasttable;
150 $g_lasttable = $tablename;
151
152 if (db_table_exists($tablename))
153 return false;
154
155 if (is_string($fieldnames))
156 $fieldnames = preg_split("/[\r\n,]/", $fieldnames);
157 if (is_string($fieldattrib))
158 $fieldattrib = preg_split("/[\r\n,]/", $fieldattrib);
159 $attribs = count($fieldattrib);
160 if (count($fieldnames) != $attribs) {
161 trigger_error(__FUNCTION__ . ": both arrays must be same length.");
162 return false;
163 }
164 $sql = "CREATE TABLE " . APPPREFIX . "$tablename (";
165 $sql .= "$idfield int(11) NOT NULL PRIMARY KEY ";
166 if ($attribs != 0) {
167 $sql .= ", ";
168
169 for($i = 0; $i < $attribs; $i++)
170 $sql .= $fieldnames[$i] . " " . $fieldattrib[$i] . ($i < $attribs - 1 ? ", " : "");
171 }
172 $sql .= ")";
173 // Send the sql command
174 $result = raw_db_query($sql);
175 if (!$result) {
176 trigger_error(__FUNCTION__ . ": could not create table $tablename.");
177 return false;
178 }
179
180 if ($valarray)
181 foreach($valarray as $values) {
182 $result = db_create_record($tablename, $fieldnames, $values, $idfield);
183 if ($result === false) {
184 return false;
185 }
186 }
187 return $result;
188}
189
190/**
191* db_delete_table()
192*
193* @param $tablename
194* @return bool "TRUE" or "FALSE"
195*/
196function db_delete_table($tablename)
197{
198 global $g_lasttable;
199
200 if (!$tablename)
201 $tablename = $g_lasttable;
202 $g_lasttable = $tablename;
203
204 if ($tablename == null || $tablename == "")
205 return false;
206 if (db_table_exists($tablename))
207 $result = raw_db_query("DROP table " . APPPREFIX . $tablename);
208 return $result;
209}
210
211/**
212* db_rename_table()
213*
214* @param $tablename
215* @param $newname
216* @return bool "TRUE" or "FALSE"
217*/
218function db_rename_table($tablename, $newname)
219{
220 return raw_db_rename_table(APPPREFIX . $tablename, APPPREFIX . $newname);
221}
222/**
223* db_list_table_fields()
224*
225* @param $tablename
226* @return array with the names of the fields of table $tablename or FALSE
227*/
228function db_list_table_fields($tablename, $type = false)
229{
230 global $g_lasttable;
231
232 if (!$tablename)
233 $tablename = $g_lasttable;
234 $g_lasttable = $tablename;
235
236 $result = raw_db_list_table_fields_def(APPPREFIX . $tablename, $type);
237 return $result;
238}
239// -------------------------------------------------------------- FIELD FUNCTIONS
240/**
241* db_create_field()
242*
243* @param $tablename
244* @param $field
245* @param $type
246* @return bool "TRUE" or "FALSE"
247*/
248function db_create_field($tablename, $field, $type)
249{
250 return raw_db_create_field(APPPREFIX . $tablename, $field, $type);
251}
252
253/**
254* db_delete_field()
255*
256* @param $tablename
257* @param $field
258* @return bool "TRUE" or "FALSE"
259*/
260function db_delete_field($tablename, $field)
261{
262 return raw_db_delete_field(APPPREFIX . $tablename, $field);
263}
264
265/**
266* db_rename_field()
267*
268* @param $tablename
269* @param $field
270* @param $newname
271* @param $type
272* @return bool "TRUE" or "FALSE"
273*/
274function db_rename_field($tablename, $field, $newname, $type)
275{
276 return raw_db_rename_field(APPPREFIX . $tablename, $field, $newname, $type);
277}
278
279/**
280* db_edit_field()
281* edit field attribute
282*
283* @param $tablename
284* @param $field
285* @param $type
286* @return bool "TRUE" or "FALSE"
287*/
288function db_edit_field($tablename, $field, $type)
289{
290 return raw_db_edit_field(APPPREFIX . $tablename, $field, $type);
291}
292// ------------------------------------------------------------- RECORD FUNCTIONS
293/**
294* db_create_record()
295*
296* Insert a new record in table $tablename.
297*
298* @param $tablename Table name. If NULL uses the table used in last function call.
299* @param unknown $fieldnames Array or CSV string with field names, one per line.
300* @param unknown $fieldvalues Array or CSV string with field values, one per line.
301* @param string $idfield
302* @return id of the affected record, FALSE if not succeded
303*/
304function db_create_record($tablename, $fieldnames = null, $fieldvalues = null, $idfield = "id")
305{
306 global $g_lasttable;
307
308 if (!$tablename)
309 $tablename = $g_lasttable;
310 $g_lasttable = $tablename;
311
312 if (!$fieldnames) {
313 $fieldnames = db_list_table_fields($tablename);
314 array_shift($fieldnames);
315 }
316 if (!$fieldvalues) {
317 $fieldvalues = array_fill(0, count($fieldnames), 0);
318
319 }
320 // Get next available index
321 $sql = "SELECT max($idfield) FROM " . APPPREFIX . $tablename;
322 $result = raw_db_query($sql);
323 if ($result === false) {
324 return false;
325 }
326 $newid = (db_fetch_array($result, FETCH_NUM)) ;
327 $newid = $newid[0] + 1;
328 // Build the two arrays
329 $names = is_string($fieldnames) ? preg_split("/[\r\n]/", $fieldnames) : $fieldnames;
330 $values = is_string($fieldvalues) ? preg_split("/[\r\n]/", $fieldvalues) : $fieldvalues;
331 if (count($names) != count($values)) {
332 trigger_error(__FUNCTION__ . ": both arrays must be same length.\n");
333 return false;
334 }
335 // Build the SQL query
336 $nfields = count($names);
337 $fieldnames = $names;
338 $fieldvalues = $values;
339 for($i = 0, $names = ""; $i < $nfields; $i++)
340 $names .= $fieldnames[$i] . ($i < $nfields - 1 ? ", " : "");
341 for($i = 0, $values = ""; $i < $nfields; $i++)
342 $values .= "'" . db_escape_string($fieldvalues[$i]) . "'" . ($i < $nfields - 1 ? ", " : "");
343
344 $sql = "INSERT INTO " . APPPREFIX . $tablename . " ($idfield, $names) VALUES ($newid, $values)";
345
346 $result = raw_db_query($sql);
347 if (!$result) {
348 trigger_error(__FUNCTION__ . ": could not create new record in table $tablename.");
349 return false;
350 }
351 return $newid;
352}
353
354/**
355* db_delete_records()
356*
357* Delete record from table $tablename.
358*
359* @param $tablename
360* @param $idarray the id or id array
361* @return bool "TRUE" or "FALSE"
362*/
363function db_delete_records($tablename, $idarray, $idfield = "id")
364{
365 global $g_lasttable;
366
367 if ($idarray == null || $idarray <= 0)
368 return false;
369 if (!is_array($idarray))
370 $idarray = array($idarray);
371
372 if (!$tablename)
373 $tablename = $g_lasttable;
374 $g_lasttable = $tablename;
375
376 foreach($idarray as $item) {
377 // Send the SQL command
378 $sql = "DELETE FROM " . APPPREFIX . $tablename . " WHERE $idfield = " . $item;
379 $result = raw_db_query($sql);
380 if (!$result) {
381 trigger_error(__FUNCTION__ . ": could not delete record $id in table $tablename.");
382 return false;
383 }
384 }
385 return true;
386}
387
388/**
389* db_edit_record()
390*
391* Edits a record from table $tablename. If $id is null, zero or < 0, inserts a new record.
392*
393* @param $tablename If NULL uses the table used in last function call.
394* @param integer $id
395* @param unknown $fieldnames Array or CSV string with field names, one per line. If NULL, affects all fields.
396* @param unknown $fieldvalues Array or CSV string with field values, one per line.
397* @param string $idfield
398* @return id of the affected record or FALSE on error
399*/
400function db_edit_record($tablename, $id = 0, $fieldnames = null, $fieldvalues = null, $idfield = "id")
401{
402 global $g_lasttable;
403
404 if ($id == null || $id <= 0) { // Create a new record
405 return db_create_record($tablename, $fieldnames, $fieldvalues, $idfield);
406 } else { // Edit existing record
407 if (!$tablename)
408 $tablename = $g_lasttable;
409 $g_lasttable = $tablename;
410 // Build the two arrays
411 if (!$fieldnames) {
412 $fieldnames = db_list_table_fields($tablename);
413 array_shift($fieldnames);
414 }
415 if (!$fieldvalues) {
416 $fieldvalues = array_fill(0, count($fieldnames), 0);
417
418 }
419
420 $names = is_string($fieldnames) ? preg_split("/[\r\n]/", $fieldnames) : $fieldnames;
421 $values = is_string($fieldvalues) ? preg_split("/[\r\n]/", $fieldvalues) : $fieldvalues;
422
423 if (count($names) != count($values)) {
424 trigger_error(__FUNCTION__ . ": both arrays must be same length.\n");
425 return false;
426 }
427 // Build the SQL query
428 $nfields = count($names);
429 for($i = 0, $str = ""; $i < $nfields; $i++) {
430 $str .= $names[$i] . "='" . db_escape_string($values[$i]) . "'" .
431 ($i < $nfields - 1 ? ", " : "");
432 }
433
434 $sql = "UPDATE " . APPPREFIX . "$tablename SET $str WHERE $idfield=$id";
435 // Send the SQL command
436 $result = raw_db_query($sql);
437 if (!$result) {
438 trigger_error(__FUNCTION__ . ": could not edit record $id in table $tablename.");
439 return false;
440 }
441 return $id;
442 }
443}
444
445/**
446* db_swap_records()
447*
448* Swaps values from two records, including the id field or not according to $xchangeid.
449*
450* @param $tablename
451* @param $id1
452* @param $id2
453* @param string $idfield
454* @param boolean $xchangeid
455* @return bool
456*/
457function db_swap_records($tablename, $id1, $id2, $idfield = "id", $xchangeid = true)
458{
459 global $g_lasttable;
460 // Table name
461 if (!$tablename)
462 $tablename = $g_lasttable;
463 $g_lasttable = $tablename;
464 $table = APPPREFIX . "$tablename";
465 // Build SQL strings
466 $result = raw_db_query("SELECT * FROM $table WHERE $idfield = $id1");
467 if (!$result) {
468 trigger_error(__FUNCTION__ . ": could not read record $id1 in table $tablename.");
469 return false;
470 }
472 $fieldvalues1 = array_values($a);
473 $fieldnames1 = array_keys($a);
474 array_shift($fieldvalues1);
475 array_shift($fieldnames1);
476
477 $result = raw_db_query("SELECT * FROM $table WHERE $idfield = $id2");
478 if (!$result) {
479 trigger_error(__FUNCTION__ . ": could not read record $id2 in table $tablename.");
480 return false;
481 }
483 $fieldvalues2 = array_values($a);
484 $fieldnames2 = array_keys($a);
485 array_shift($fieldvalues2);
486 array_shift($fieldnames2);
487 // Exchange values
488 if (db_edit_record($tablename, $id1, $fieldnames2, $fieldvalues2, $idfield) === false) return false;
489 if (db_edit_record($tablename, $id2, $fieldnames1, $fieldvalues1, $idfield) === false) return false;
490 // Exchange id's
491 if ($xchangeid) {
492 $unique = db_get_next_free_id($tablename);
493 if (db_edit_record($tablename, $id1, array($idfield), array($unique), $idfield) === false) return false;
494 if (db_edit_record($tablename, $id2, array($idfield), array($id1), $idfield) === false) return false;
495 if (db_edit_record($tablename, $unique, array($idfield), array($id2), $idfield) === false) return false;
496 }
497 return true;
498}
499
500/**
501* db_get_data()
502*
503* Reads data from table $tablename.
504*
505* $tablename Table name. If NULL uses the table used in last function call.
506* $id Identifier(s). May be an array or a CSV string
507* $col Column(s) or field(s). May be an array or a CSV string
508* $where Additional WHERE clause
509* $result_type May be FETCH_ASSOC, FETCH_BOTH or FETCH_NUM
510* $idfield Name of id field
511* $orderby Additional ORDER BY clause
512*
513* $id $col returns
514* --------------------------------------------------------------------
515*
516* int null array with the whole record $id
517* int str the value of column $col from record $id
518* int str[] array with column values in array $col of record $id
519* int[] null array of arrays with values from all columns of the $id registers
520* int[] str array with the values of column $col from the $id registers
521* int[] str[] 2-D array with the values of columns $col from the $id registers
522* null null array of arrays with the whole table
523* null str array with values of the $col column from the whole table
524* null str[] array of arrays with the values of the columns $col from all table
525*
526* @param $tablename
527* @param unknown $id
528* @param unknown $col
529* @param string $where
530* @param unknown $result_type
531* @param string $idfield
532* @param string $orderby
533* @return result or FALSE
534*/
535function db_get_data($tablename, $id = null, $col = null, $where = "", $result_type = FETCH_NUM, $idfield = "id", $orderby = "")
536{
537 global $g_lasttable;
538
539 if (!$tablename)
540 $tablename = $g_lasttable;
541 $g_lasttable = $tablename;
542
543 if (is_array($col))
544 $col = implode(",", $col);
545 if ($col === null || $col === "")
546 $col = "*";
547 // Build the WHERE clause
548 if ($id !== null) {
549 if (is_string($id) && strstr($id, ",")) {
550 $id = explode(",", $id);
551 }
552 if (is_array($id)) {
553 $idcond = "";
554 for($i = 0; $i < count($id); $i++)
555 $idcond .= "$idfield = '{$id[$i]}'" . ($i < count($id) - 1 ? " OR " : "");
556 } else
557 $idcond = "$idfield = '$id'";
558
559 $condition = $where ? " WHERE ($where) AND ($idcond)" : " WHERE ($idcond)";
560 } else
561 $condition = $where ? " WHERE ($where)" : "";
562
563 $orderby = $orderby ? " ORDER BY $orderby" : "";
564 // Do the query
565 $sql = "SELECT $col FROM " . APPPREFIX . $tablename . $condition . $orderby;
566
567 $result = raw_db_query($sql);
568 if (!$result)
569 return false;
570 // Loop to build the return array
571 $array = array();
572 while ($row = db_fetch_array($result, $result_type)) {
573 if (count($row) == 1)
574 $row = array_shift($row);
575 $array[] = $row;
576 }
577 if (db_free_result($result) === false) return false;
578 // Return the result
579 if (!is_array($array))
580 return $array;
581
582 switch (count($array)) {
583 case 0:
584 return false;
585
586 case 1:
587
588 $test = $array; // Copy array
589 $elem = array_shift($test); // 1st element of array...
590 if (is_null($elem)) // ...is it null?
591 return false; // Yes: return null
592 if (is_scalar($elem)) // ...is it a scalar?
593 return $elem; // Yes: return the element alone
594 else
595 return $array; // No: return the whole array
596 default:
597 return $array;
598 }
599}
600
601/**
602* db_get_index()
603*
604* Returns the index of the record identified by $id
605*
606* @param $tablename
607* @param $id
608* @param string $idfield
609* @return index or FALSE
610*/
611
612function db_get_index($tablename, $id, $idfield = "id")
613{
614 $data = db_get_data($tablename, null, $idfield);
615 return array_search($id, $data);
616}
617
618/**
619* db_get_id()
620*
621* Returns the id of the record indexed by $index
622*
623* @param $tablename
624* @param $index
625* @param string $idfield
626* @return id or FALSE
627*/
628
629function db_get_id($tablename, $index, $idfield = "id")
630{
631 global $g_lasttable;
632
633 if (!is_scalar($index)) {
634 trigger_error(__FUNCTION__ . ": index must be an integer");
635 return false;
636 } else
637 $index = (int)$index;
638
639 if (!$tablename)
640 $tablename = $g_lasttable;
641 $g_lasttable = $tablename;
642
643 // Do the query
644 $sql = "SELECT $idfield FROM " . APPPREFIX . $tablename . " LIMIT 1 OFFSET $index";
645
646 $result = raw_db_query($sql);
647 if (!$result)
648 return false;
649
651
652 if (db_free_result($result) === false)
653 return false;
654
655 return $ret[0];
656}
657
658/**
659* db_get_next_free_id()
660*
661* Returns the next available id in table $tablename.
662*
663* @param $tablename
664* @param string $idfield
665* @return id or FALSE
666*/
667function db_get_next_free_id($tablename, $idfield = "id")
668{
669 global $g_current_db;
670 global $g_lasttable;
671
672 if (!$tablename)
673 $tablename = $g_lasttable;
674 $g_lasttable = $tablename;
675
676 $sql = "SELECT max($idfield) FROM " . APPPREFIX . $tablename;
677 $result = raw_db_query($sql);
678 if (!$result) {
679 return false;
680 }
681 $maxid = (db_fetch_array($result, FETCH_NUM)) ;
682
683 return $maxid[0] + 1;
684}
685// ---------------------------------------------------------------- SQL FUNCTIONS
686/**
687* depricated
688* exists only for compatibility to previous version
689* is the same as raw_db_query
690* does not handle APPPREFIX
691*/
692
693function db_query($query)
694{
695 return raw_db_query($query);
696}
697
698/**
699* db_fetch_array()
700*
701* @param $result
702* @param $type
703* @return array
704*/
706{
707 /**
708 * array mysql_fetch_array ( resource result [, int result_type])
709 * int type MYSQL_ASSOC, MYSQL_NUM ( == fetch_row), and MYSQL_BOTH
710 */
711
712 return raw_db_fetch_array($result, $type);
713}
714
715/**
716* db_free_result()
717*
718* @param $result
719* @return bool "TRUE" or "FALSE"
720*/
722{
724}
725
726/**
727* db_escape_string()
728*
729* @param $str
730* @return string escaped
731*/
732function db_escape_string($str)
733{
734 /**
735 * string mysql_real_escape_string ( string unescaped_string [, resource link_identifier])
736 */
737
738 return raw_db_escape_string($str);
739}
740// ------------------------------------------------------------------ END OF FILE
741
742?>
$result
db_get_id($tablename, $index, $idfield="id")
db_escape_string($str)
db_swap_records($tablename, $id1, $id2, $idfield="id", $xchangeid=true)
db_get_next_free_id($tablename, $idfield="id")
db_rename_table($tablename, $newname)
db_delete_field($tablename, $field)
$_mainpath
db_get_info($info="")
db_edit_record($tablename, $id=0, $fieldnames=null, $fieldvalues=null, $idfield="id")
const DB_WRAPVERSION
db_free_result($result)
db_list_database_tables()
db_get_data($tablename, $id=null, $col=null, $where="", $result_type=FETCH_NUM, $idfield="id", $orderby="")
db_table_exists($tablename)
db_list_table_fields($tablename, $type=false)
db_create_record($tablename, $fieldnames=null, $fieldvalues=null, $idfield="id")
db_create_table($tablename, $fieldnames, $fieldattrib, $idfield="id", $valarray=null)
db_query($query)
db_open_database($database, $server="", $username="", $password="")
db_create_database($database, $server="", $username="", $password="")
db_close_database()
db_edit_field($tablename, $field, $type)
db_rename_field($tablename, $field, $newname, $type)
db_delete_table($tablename)
db_fetch_array($result, $type=FETCH_NUM)
db_delete_records($tablename, $idarray, $idfield="id")
db_get_index($tablename, $id, $idfield="id")
db_create_field($tablename, $field, $type)
raw_db_edit_field($tablename, $field, $type)
if(DB_WRAPVERSION !=DB_MYSQL_WRAP) raw_db_open_database($database, $server="", $username="", $password="")
raw_db_create_database($database, $server="", $username="", $password="")
raw_db_delete_field($tablename, $field)
raw_db_close_database()
raw_db_list_table_fields_def($tablename, $type=false)
raw_db_rename_field($tablename, $field, $newname, $type)
raw_db_list_database_tables()
const FETCH_NUM
raw_db_create_field($tablename, $field, $type)
const FETCH_ASSOC
raw_get_db_version()
raw_db_table_exists($tablename)
raw_db_fetch_array($result, $type=FETCH_BOTH)
raw_db_rename_table($tablename, $newname)
raw_db_query($query)
raw_db_free_result($result)
raw_db_escape_string($str)