Source for file OCSP_DB_mySQL.phpclass
Documentation is available at OCSP_DB_mySQL.phpclass
* Class file mySQL.phpclass
* @project Open CSP-Management
* @author Peter Krebs <pitlinz@users.sourceforge.net>
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* @todo move the function in $PROJECT['PHPINCPATH']."db/mySQL.phpinc";
* into the class to be able to server several database at once
* @version pk-04-12-21 $GLOBALS['PROJECT'] -> $GLOBALS['OCSP']
require
dirname(__FILE__
) .
_OCSP_DIRSEP_ .
"INFA_OCSP_DBOBJ.phpclass";
require_once dirname(__FILE__
) .
_OCSP_DIRSEP_ .
"OCSP_DB.phpclass";
require_once dirname(__FILE__
) .
_OCSP_DIRSEP_ .
"OCSP_CURSOR_mySQL.phpclass";
* handels mySQL database connections / operations
* @project Open CSP-Management
* @author Peter Krebs <pitlinz@users.sourceforge.net>
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* ------------------------------------------------
* @version pk-07-04-12 parent class OCSP_DB added
* array of already seen tables definitions
* @staticvar array $dbTableDefinitions
static $dbTableDefinitions =
array();
* @var resource $myConnId
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
* disconnect from the database
$this->isConnected =
False;
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// ##############################################
* connects to the database
* @param string $conffile file containing the database configuration
* @param boolean $asPublic use public user from the conf
* @param boolean $asAdmin use the admin user from the conf
function connect($conffile=
"",$asPublic=
True,$asAdmin=
False,$debug=
False) {
if (!empty($conffile) &&
file_exists($str_projPath .
$conffile))
$conffile =
$str_projPath .
$conffile;
$conffile =
$str_projPath .
$conffile;
if (file_exists($str_projPath .
"config/" .
$conffile))
$conffile =
$str_projPath .
"config/" .
$conffile;
// finaly try mysql (default)
if (file_exists($str_projPath .
"config/mySQL.phpconf"))
$conffile =
$str_projPath .
"config/mySQL.phpconf";
throw
new Exception('no db confinguration file found (' . __FILE__ .
" Line: " . __LINE__
);
} // if (!empty($conffile) && file_exists($conffile)) -> else
if (!isset
($DBCONF[$s_key]['USR']))
die(get_class($this).
" Line: ".__LINE__.
" ERROR no \$DBCONF[".
$s_key.
"] array in ".
basename($conffile).
" ");
$this->myDB =
$DBCONF['DATABASE'];
if ($debug) echoDebugLine(__FILE__
,__LINE__
,"Connecting to ".
$this->myServer.
" as ".
$DBCONF[$s_key]['USR'].
" ($key)");
die(get_class($this).
" Line: ".__LINE__.
" ERROR conffile ".
basename($conffile).
" ERROR connecting to ".
$this->myServer.
" as $dbUser");
die(get_class($this).
" Line: ".__LINE__.
" ERROR conffile ".
basename($conffile).
" using DB ".
$this->myDB.
" as $dbUser");
//echoDebugLine(__FILE__,__LINE__,get_class($this).": estabilshed a database connection");
if ($debug) echo
"<p>done connecting</p>";
##############################################
return $this->connect($conffile,True,False,$debug);
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* this is not required for mysql
* returns an array with the main parts of an select
* the returned array has the following indexes
$s_curKey=
$a_elements[0];
foreach ($a_elements as $s_elem) {
$a_ret[$s_curKey].=
$s_elem.
" ";
* checks a query string if it's save to use
* @param int $type PQT_[querytype]
* @todo only PQT_SELECT and PQT_UNION are checked for the moment
function checkQuery($aQuery,$type=
PQT_SELECT,$debug=
False) {
if (strstr($aQuery,";")) { // disable ; in query
ocsp_logError(__FILE__
,__LINE__
,"$type not the first statement");
* @param string $msg addintinal message to echo
* returns the last mySQL error message
* returns the last mySQL error nr
* opens a cursor for a query
* @param string $aQuery the sql query
* @param boolean $secMode
* @param boolean $withErrMsg
* @param boolean $autoFree
* @param boolean $useBuffer
* @returns OCSP_CURSOR_mySQL
function query($aQuery=
"",$secMode=
True,$withErrMsg=
False,$autoFree=
True,$useBuffer=
True) {
* returns (a column) of the first row match
* if $colNr > -1 the column value at position $colNr in
* the select statement is returned (NOTE: index starts at 0)
* if $colNr < 0 a array is returend
* if $usNames the DB-column names are the index otherwise
* the index of the returned are is the number in the select order
* @param boolean $withErrMsg
* @param boolean $useNames
* @param boolean $secMode
function quickQuery($aQuery,$colNr=-
1,$withErrMsg=
False,$useNames=
True,$secMode=
True,$debug=
False) {
if ($debug) echo
"<p><b>DB_mySQL::quickQuery(\$aQuery,$colNr,$withErrMsg,$useNames,$secMode,$debug)</b> (".
get_class($this).
")</p>";
if ($debug) echo
"<blockquote><pre>quickQuery: $aQuery</pre></blockquote>";
$ret=
$cursor->fetchArrayNum($colNr);
$this->errorMsg("quickQuery: \n$aQuery");
if ($debug) echo
"<blockquote>RETURNS: <pre>".
pcf_print_r($ret).
"</pre></blockquote>";
* returns an array of table rows
* if $keyFld == $valueFld
* a simple array is returned
* if $keyFld != $valueFld
* a simple array is returned where $keyFld is used as index
* ( $array[$key]=$value )
* a named 2 dimensonal array is returned
* if $keyFld == -1 && $valueFld == -1
* a 2 dimensonal array is returned
* @param string $aQuery a sql select statement
* @param int $keyFld index of the key field in the select result (starts at 0)
* @param int $valueFld index of the value field in the select result (starts at 0)
* @param boolean $secMode check query whith DB_mySQL::checkQuery()
* @param boolean $debug show debug info
function queryArray($aQuery,$keyFld=
0,$valueFld=
0,$secMode=
True,$debug=
False)
if ($debug) echoDebug(__FILE__
,"<p>Query:<br/>".
$aQuery.
"</p>");
if ($debug) echoDebugLine(__FILE__
,__LINE__
,"returning row array");
while ($row=
$cursor->fetchArray()) {
} else if ($keyFld ==
$valueFld) {
while ($val=
$cursor->fetchArrayNum($keyFld)) {
if ($debug) echoDebug(__FILE__
,"<p>Value: $val</p>");
while ($row=
$cursor->fetchArray()) {
if ($debug) echo
$row[$keyFld].
"==".
$row[$valueFld].
"<br />";
$ret[$row[$keyFld]]=
$row[$valueFld];
$this->errorMsg("queryArray: \n$aQuery");
if ($debug) echoDebugLine(__FILE__
,__LINE__
,"$aQuery failed \n returning False");
* generates a query and returns an array of the resultset
* limit <> a multidimensional array is returned (see queryArray)
* if limit = 1 a single array is returned (see quickQuery)
* if the column starts with a ? the value is assumed to be an sql statement
* else column=slashedvalue(value) is added to the query
* @param string $aTable (the table name)
* @param array $conditions (array(COLUMN => VALUE)) if VALUE does not starts with a '¿' t
* @param int $limit (0 is unlimeted)
* @param string $orderBy (comma seperated list of fields to order)
* @version pk-07-09-08 '?' coll added
function getArray($aTable,$conditions=
NULL,$offset=
0,$limit=
0,$orderBy=
"",$debug=
False)
$str_query=
"SELECT * FROM ".
$aTable;
if ($conditions &&
sizeof($conditions))
foreach($conditions as $str_col =>
$m_val)
if (substr($str_col,0,1)==
'?') // <pk-07-09-08>
//$str_query.=$str_whereAnd.substr($m_val,1);
// <pk-08-01-25 why substr ????
$str_query .=
$str_whereAnd .
$m_val;
$str_query.=
" ORDER BY ".
$orderBy;
return $this->quickQuery($str_query,-
1,False,True,True,$debug);
return $this->queryArray($str_query,-
1,-
1,True,$debug);
return $aCursor->numOfRows();
return $aCursor->fetchArrayFld();
return $aCursor->fetchArray();
* converts php variables to db save values adds slashes and " to enclose strings
* - datetime,date,time: #NOW #NOW_DATE #NOW_TIME
* - timestamp: NOW() CURRENT_TIMESTAMP
* @param string $aType database type
* @param mixed $aValue column value
* @param int $maxLen max Field Len
* @param boolean $debug show debug info
* @version pk-05-01-13 tinyint added
* @version pk-05-05-18 bugfix timestamp
* @version pk-05-11-25 special value added
* @version pk-06-11-28 double added changes in default
function checkValue($aType,$aValue,$maxLen=
255,$debug=
False) {
if ($debug) echo
"<p><b>DB_mySQL::checkValue($aType,".
htmlspecialchars(substr($aValue,0,10)).
"...,$maxLen)</b></p>";
switch (strtolower($aType)) { /* <pk-05-01-13 strtolower() added /> */
case "tinyint":
/* <pk-05-01-13 /> */
if (($aValue ===
False) ||
($aValue ===
0) ||
($aValue ===
"0")) return 0;
// NOTE === type compare because empty("0") returns True
strings can be treaten as blob because
mysql cuts the string if to it's to long
if (!strlen($aValue)) return "NULL";
return "'".substr(addslashes($aValue),0,$maxLen)."'";
case "float":
// <pk-06-09-06 />
case "double":
// <pk-06-11-28 />
return doubleval($aValue); // <pk-06-10-10 />
if (!strlen($aValue)) return "NULL";
case "timestamp":
// <pk-05-10-04>
if ($debug) echo
"<p>Timestamp is NULL -> return 0 to avoid NOW()<p>";
if ($debug) echo
"<p>Checking Timestamp: $aValue -- ".
$this->quickQuery($s_query,0).
"</p>";
if ($debug) echo
"<p>DBVALUE: $s_dbValue</p>";
case "date":
// <pk-05-11-25>
case "time":
// <pk-05-11-25>
case "datetime":
// <pk-05-11-25>
if ($aValue==
"NULL") // <pk-06-08-18>
return "'".
date('Y-m-d H:i:s',time()).
"'";
if ($aValue==
"\$#NOW_DATE\$")
if ($aValue==
"#NOW_TIME")
if ((empty($aValue)) &&
(strval($aValue) !==
'0')) // a string with only one 0 also is empty //<pk-06-11-28 />strval added
* logs sql command (SELECTS ARE NOT LOGGED)
* if !empty($GLOBALS['PROJECT']['DBLOG'])
* $GLOBALS['PROJECT']['DBLOG'] logfile
* if ((!empty($GLOBALS['PROJECT']['DBADMINLOG'])) && (strpos($mystring, $findme) !== False))
* $GLOBALS['PROJECT']['DBADMINLOG'] logfile
* @param strint $aQuery the query
if (!empty($GLOBALS['PROJECT']['DBLOG'])) {
if ($logFile=
fopen($GLOBALS['PROJECT']['DBLOG'],'a')) {
if (isset
($_SESSION['USER']) &&
(is_object($_SESSION['USER']))) {
fwrite($logFile,time().
"\t".
$_SESSION['USER']->userId.
"\t".
$aQuery.
"\n");
* @param string $aCmd the cmd
* @param boolean $debug show debug info
* @param boolean $secMode test a aCmd - not used now
* return mixed mysql_query($aCmd,$this->myConnId)
* @todo check $aCmd in secMode
function executeCmd($aCmd,$debug=
False,$secMode=
True) {
echo
"<p><b>DB_mySQL::executeCmd(\$aCmd,$debug,$secMode)</b> (".
get_class($this).
")</p>";
echo
"<blockquote><pre style=\"font-size:9px\">".
htmlspecialchars($aCmd).
"</pre>";
throw
new Exception('MySQL Error: ' .
mysql_error() .
" (Query: " .
$aCmd .
")");
if ($debug) echo
"</blockquote>";
* execute an insert statement and returns True or generated auto-key
* inserts a new row with $aQuery
* returns the value of the auto_increment field or True
* in case of an error it returns False
* @param string $query a Insert statement
* @param string $aTable name of the table to insert the column
* @param string $keyfld auto-key (autoincremnt column)
* @param boolean $withLock lock table during insert (to get the key)
* @param boolean $debug show debug information
* @returns int key of auto-key or True on success False in case of error
* @version pk-06-07-22 debug info
* @version pk-06-10-30 no lock without a keyfld
function insert($query,$aTable=
"",$keyfld=
"",$withLock=
True,$debug=
False) {
echo
"<blockquote style=\"font-size:90%\">";
if ((empty($aTable)) ||
(empty($keyfld))) { // <pk-06-10-30 />
if ($debug) echo
"<p color=red>False</p></blockquote><hr />";
$this->logCmd($query); // log only succesful commands
if ($debug) echo
"<p color=green>Return: $newId</p></blockquote>";
if ($debug) echo
"<p color=green>Return: True</p></blockquote>";
// ------------------------------------------------------
// data manipulation methods
// ------------------------------------------------------
* creates an insert statement and returns $this::insert()
* @see DB_mySQL::insert()
*iinserts a new row out of an array
* returns the value of the auto_increment field or True
* in case of an error it returns False
* @param string $table name of the table to insert
* @param array $valueArr key=>value array
* @param boolean $debug show debug information
* @returns int key of auto-key or True on success False in case of error
* @version pk-05-01-13 debuginfos
* @version pk-06-07-22 phpwarning
* @version pk-07-08-02 adding $idFld param
function insertArray($table,$valueArr,$debug=
False,$idFld=
"")
if ($debug) echoDebugMethod(__FILE__
,get_class($this),"DB_mySQL::insertArray()","Table: $table\n<pre style=\"font-size:75%;padding-left:20px;color: #FF0C0C\">".
print_r($valueArr,True).
"</pre>");
if (empty($table)) return False;
$query=
"INSERT INTO $table (";
while ((list
($key,$fld)=
each($tblDesc)) &&
empty($idFld)) {
if ($fld['AUTO_INCREMENT']) $idFld=
$key;
// while(list($key,$value) = each($valueArr)) {
foreach($valueArr as $key =>
$value) {
if (isset
($tblDesc[$key])) {
if (!empty($value) ||
(strval($value)===
"0")) { // <pk-06-08-18> do not check NULL values
// the db should decide what to do if the column is not set.
if ($debug >
3) echo
"<pre>$key ($value)(".
$tblDesc[$key]['TYPE'].
")=".
$this->checkValue($tblDesc[$key]['TYPE'],$value,$tblDesc[$key]['LEN']).
"</pre>";
if ($debug) echo
"<p>$key:</p><blockquote><hr />";
if (!isset
($tblDesc[$key]['LEN'])) $tblDesc[$key]['LEN']=
NULL; // <pk-06-07-22 />
$val=
$this->checkValue($tblDesc[$key]['TYPE'],$value,$tblDesc[$key]['LEN'],$debug);
if ($debug) echo
"<hr /></blockquote><pre style=\"font-size:75%\">Value: ".
htmlspecialchars($val).
"</pre>";
if ($debug) echo
"<p>$key is NULL -> not added into state</p>";
if ($debug) echo
"<p>$key not in $table</p>";
$query .=
") VALUES ".
$values.
")";
if ($debug) echo
"<p style=\"font-size:8px;\">$query</p></blockquote>";
return $this->insert($query,$table,$idFld,True,$debug);
* replace existing row or insert now if not exists
* inserts a row or update an existing row
* all existing values not in $valueArr (assoc)
* will be handeld by db spezifaction
* see mysql Doc: {@link http://www.mysql.com/doc/en/REPLACE.html}
* @param string $table name of the DBTABLE
* @param array $valueArr value array with FIELDNAME as Index
* @param boolean $debug show debug information
* @returns bool True on success False in case of error
* @version pk-05-12-28 set auto_increment column in valueArr on insert
if ($debug) echoDebug(__FILE__
,"<p><b>DB_mySQL::replaceArray($table,\$valueArr (".
sizeof($valueArr).
"),$debug)</b></p><blockquote style=\"font-size:90%\">",2);
if (empty($table)) return False;
$query=
"REPLACE INTO $table (";
foreach($tblDesc as $s_col=>
$a_desc) {
// check if we have to insert the row (empty primary_key)
if ($a_desc['PRIMARY_KEY'] &&
empty($valueArr[$s_col])) {
// we have an empty primary key
if ($a_desc['AUTO_INCREMENT']) {
// which is an auto_increment column
if ($valueArr[$s_col]=
$this->insertArray($table,$valueArr,$debug)) {
// ok we have inserted a new row and set the new id to the valueArr
return intval($valueArr[$s_col]);
while(list
($key,$value) =
each($valueArr))
/* <pk-04-08-10 /> (is_array($tblDesc[$key]) added */
if ((isset
($tblDesc[$key])) &&
(is_array($tblDesc[$key])) &&
(!intval($key)) &&
($key !==
0)) {
//if ($debug) echoDebug(__FILE__,"<p><b>COLUMN: </b>$key</p><blockquote>",2);
if (!isset
($tblDesc[$key]['LEN'])) $tblDesc[$key]['LEN']=
NULL;
$values .=
$sep.
$this->checkValue($tblDesc[$key]['TYPE'],$value,$tblDesc[$key]['LEN'],False);
//if ($debug) echoDebug(__FILE__,"</blockquote>",2);
if ($debug) echoDebugLine(__FILE__
,__LINE__
,"<p>Query: ".
$query.
") <br /> VALUES ".
$values.
")");
$query .=
") VALUES ".
$values.
")";
if ($debug) echoDebug(__FILE__
,"<p>DONE</p></blockquote><hr>",2);
if ($debug) echo
echoDebug(__FILE__
,"<p>ERROR</p></blockquote><hr>",2);
* updates $values in $aTable where $conditions
* @param array $conditions
* @return int number of effekted rows
function updateArray($aTable,$conditions,$values,$limit=
0,$debug=
False)
$str_query =
"UPDATE " .
$aTable .
" SET";
foreach($values as $str_col =>
$mix_val)
if (isset
($arr_tblDesc[$str_col]))
$str_whereAnd =
" WHERE ";
foreach($conditions as $str_col =>
$mix_val)
if (substr($str_col,0,1)==
"?")
$str_query.=
$str_whereAnd.
$mix_val;
} else if (substr($str_col,0,1)==
"~") {
if ($debug) echoDebugLine(__FILE__
,__LINE__
,"SQL-Command: \n".
$str_query .
"\n");
* deletes an existing row where the primary key must be set in $valueArr
* @param string $table name of the DBTABLE
* @param array $valueArr value array with FIELDNAME as Index
* @param boolean $debug show debug information
* @returns bool True on success False in case of error
public function deleteArray($table,&$valueArr,$debug=
False)
$arr_conditions =
array();
foreach($arr_tblDesc as $str_col =>
$arr_desc)
if ($arr_desc['PRIMARY_KEY'])
if (empty($valueArr[$str_col]))
// unable to identify the row
$arr_conditions[$str_col] =
$this->checkValue($arr_desc['TYPE'],$valueArr[$str_col],$arr_desc['LEN'],False);
// method requires to identify the row
$str_query =
"DELETE FROM " .
$table .
" WHERE";
foreach($arr_conditions as $str_col =>
$str_val)
$str_query .=
$str_sep .
" " .
$str_col .
"=" .
$str_val;
if ($debug) echoDebugLine(__FILE__
,__LINE__
,"SQL-Command: ".
$str_query);
* replace existing row or insert now if not exists
* calls: <code>return $this->replaceArray($table,$valueArr,$debug);</code>
* @see DB_mySQL::replaceArray()
* @param string $table name of the DBTABLE
* @param array $valueArr value array with FIELDNAME as Index
* @param boolean $debug show debug information
* @deprecated since pk-05-01-01
function replace($table,$valueArr,$debug=
False) {
if ($debug) echo
"<p><b>DB_mySQL::replace($table,\$valuArr,...)</b>(".
get_class($this).
"</p>";
* deletes a row form the database
* note delKeys must have at least one key => value element
function deleteRows($table,$delKeys,$backup=
True,$debug=
False)
if (!is_dir($str_backupDir)) {
ocsp_logError(__FILE__
,__LINE__
,"could not create backupdir: $str_backupDir");
if ($arr_backup=
$this->getArray($table,$delKeys))
if ($r_fp=
fopen($str_backupDir.
"/".
$dbl_timestamp.
".bak",'w')) {
return True; // the rows does not exists
$str_cmd=
"DELETE FROM $table WHERE ";
foreach($delKeys as $str_col =>
$m_val)
if ($debug) echoDebugLine(__FILE__
,__LINE__
,"Delete Cmd: \n".
$str_cmd.
"\n");
$str_backupFile .=
time() .
".unload";
$str_cmd =
"SELECT * FROM " .
$aTable;
$str_cmd.=
" INTO OUTFILE '" .
$str_backupFile .
"'";
$str_cmd =
"TRUNCATE TABLE " .
$aTable;
* resorts orderfields in a table (remove gaps)
* orderfields are integers from 1 to ...
* the are used to let the user change order
* @param string $table the table
* @param string $orderFld the order column
* @param string $where the where clause with the keyword WHERE
* do not add things like group by or limit ....
* @param string $debug show debug info
* @param string $orderby order by prepend (SELECT .... ORDER BY $orderby,$orderFld)
* @param string $groupbyCol restart index when col change
function resortTable($table,$orderFld,$where=
"",$debug=
False,$orderby=
"",$groupbyCol=
"",$startIdx=
1) {
if ($debug) echoDebug(__FILE__
,"<p><b>DB_mySQL::resortTable($table,$orderFld,$where,$debug)</b> (".
get_class($this).
")</p>",1);
if (!stristr($tblDesc[$orderFld]['TYPE'],"int")) {
// $orderFld is not of a valid type or does not exists in the table
// get the primary_key columns
foreach($tblDesc as $s_col =>
$a_colDesc) {
if ($a_colDesc['PRIMARY_KEY']) {
if ($debug) echoDebug(__FILE__
,"<p>Primary Key Column(s): ".
implode(",",$a_PKCols).
"</p>",2);
if (!empty($groupbyCol)) // <pk-07-08-08 /> E_ALL
if (!empty($orderby)) $orderby.=
",";
$s_query =
"SELECT * FROM ".
$table.
" ".
$where;
$s_query.=
" ORDER BY ".
str_replace(",,",",",$s_grpBy.
$orderby).
$orderFld;
if ($debug) echoDebug(__FILE__
,"<p>$s_query</p>",2);
if ($a_Rows=
$this->queryArray($s_query,-
1,-
1,False,False)) {
// now we have an array of all rows
foreach($a_Rows as $i_nr =>
$a_curRow) {
if ((!empty($groupbyCol)) &&
($a_curRow[$groupbyCol] !=
$s_grpValue)) {
// new group -> restart index
$s_grpValue=
$a_curRow[$groupbyCol];
if (intval($a_curRow[$orderFld]) !=
$i_idx) {
// we have to change the row
$s_cmd =
"UPDATE $table SET $orderFld=$i_idx";
$s_cmd.=
" WHERE $orderFld=".
intval($a_curRow[$orderFld]);
foreach($a_PKCols as $s_PKCol) {
if ($debug) echoDebug(__FILE__
,"<p>UPDATE: $s_cmd</p>",1);
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
/* construct / init / objvar methods */
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
* returns the mysql server info()
return "-- NOT CONNECTED --";
* returns an array with column description arrays for each column
* where column name is the array index
* a column description array has the following elements
* - string ['TYPE'] (type of the column example varchar,int,...)
* - int ['LEN'] (length of the column if supported by type)
* - string ['FLAGS'] (mysql flags)
* - boolean ['AUTO_INCREMENT'] (does the column use auto values on insert)
* - boolean ['NULL'] (null allowed)
* - boolean ['PRIMARY_KEY'] (the column is part of the primary key)
* - boolean ['KEY'] (the column is part of a -none primary- key)
* - string ['COLNAME'] (the name of the column - same as array index should be)
* @param bool $debug pk-03-10-24
* @version pk-05-01-12 php: function mysql_list_fields() is deprecated
* @version pk-06-02-09 error handling
* @version pk-07-08-04 ['TABLE'] added to the column desc
* @version pk-08-03-11 use $dbTableDefinitions
if ($debug) echoDebug(__FILE__
,"<p><b>DB_mySQL::getDBTblDesc($table,$debug)</b> (".
get_class($this).
")</p>",0);
if (empty($table)) return array();
return OCSP_DB_mySQL::$dbTableDefinitions[$table];
$descArr=
$this->queryArray($query,0,-
1,False,$debug);
if (!is_array($descArr)) { // <pk-06-02-09>
if ($debug) echoDebug(__FILE__
,"<p>Query: $query failed</p>",2);
foreach($descArr as $colName =>
$colDesc) {
$typArr =
explode("(",$colDesc['Type']);
$ret[$colName]['TYPE'] =
$typArr[0];
if (!empty($typArr[1])) {
if (!empty($colDesc['Extra'])) {
$ret[$colName]['FLAGS'] =
explode(" ",$colDesc['Extra']);
$ret[$colName]['AUTO_INCREMENT']=
(strstr($colDesc['Extra'],"auto_increment")) ?
True :
False;
$ret[$colName]['NULL'] =
(substr($colDesc['Null'],0,1) ==
"Y");
$ret[$colName]['PRIMARY_KEY'] =
($colDesc['Key']==
"PRI");
$ret[$colName]['DEFAULT'] =
$colDesc['Default'];
$ret[$colName]['KEY'] =
$colDesc['Key'];
$ret[$colName]['COLNAME'] =
$colName;
$ret[$colName]['TABLE'] =
$table; // <pk-07-08-04 />
if (!$ret[$colName]['NULL']) $ret[$colName]['FLAGS'][]=
"not_null";
if ($ret[$colName]['PRIMARY_KEY']) $ret[$colName]['FLAGS'][]=
"primary_key";
if ($debug) echoDebug(__FILE__
,"<pre style=\"font-size:50%\">".
print_r($ret,True).
"</pre>",1);
/* <pk-05-01-12> php: function mysql_list_fields() is deprecated */
* returns an array with all primary key column names
if ($debug) echoDebug(__FILE__
,"<p><b>DB_mySQL::getPrimaryKeys($aTbl)</b> (".
get_class($this).
")</p>",0);
foreach($a_tblDesc as $s_colName =>
$a_colDesc) {
if ($a_colDesc['PRIMARY_KEY']) {
* returns an array with all tables in the database
* @param bool $debug since pk-03-10-25
* @version pk-05-01-12 (php: function mysql_list_tables() is deprecated)
$query=
"SHOW TABLES FROM ".
$this->myDB;
if ($cursor=
$this->query($query)) {
while ($row=
$cursor->fetchArray()) {
if (!sizeof($ret) ||
empty($ret[0])) {
$this->errorMsg("DB_mySQL::getDBTblList");
if ($debug) { echo
"<pre>$query\n";print_r($ret);echo
"</pre>"; }
if ($debug) {echo
"<blockquote><p>DB_mySQL::getDBTblList RETURN: array with ".
count($ret).
" elements</p></blockquote>";}
* checks if a table exists
* @param string $aTable table name
* @param boolean $debug since pk-03-10-24
if ($debug) echo
"<hr /><p><b>DB_mySQL::tblExists($aTable,$debug)</b></p><blockquote>";
if (!$ret=
in_array($aTable,$tblLst,False)) {
if ($debug) { echo
"<pre style='font-size:10px;'>Searching $aTable in:\n";print_r($tblLst);echo
"</pre>"; }
// sometimes in_array fails
while ((!$ret) &&
(list
($key,$tbl)=
each($tblLst))) {
if ($debug) echo
"<p>tblExists RETURN $ret</p></blockquote>";
if ($debug) echo
"<p>RETURN False</p></blockquote>";
return False; // NO TABLES FOUND
public function createTable($tblName,$cols,$debug=
False)
$str_cmd =
"CREATE TABLE " .
$tblName .
"(";
foreach($cols as $str_colName =>
$arr_colDesc)
$str_cmd .=
$cha_sep .
$str_colName .
" " .
$str_colDesc;
$str_cmd.=
") ENGINE = MYISAM CHARACTER SET utf8 COLLATE utf8_bin";
* returns an array of table column names
* returns if a table has a certain column
if ($debug) echo
"<p><b>DB_mySQL::tblHasColumn($table,$colName)</b> (".
get_class($this).
")</p>";
return (isset
($a_tblDesc[$colName]));
* returns the database column definition to use in create table or alter column
* @param array $dbDesc Column array generated with DB_MYSQL::getDBTblDesc()
if (!isset
($dbDesc['TYPE']) ||
empty($dbDesc['TYPE']))
if ($debug) ocsp_logError(__FILE__
,__LINE__
,'no type set in \$dbDesc',E_WARNING);
if (!intval($dbDesc['LEN'])) $dbDesc['LEN']=
255;
else $dbDesc['LEN']=
intval($dbDesc['LEN']);
$ret =
" VARCHAR(".
($dbDesc['LEN'] >
255 ?
255 :
$dbDesc['LEN']).
") ";
$ret .=
"CHARACTER SET utf8 COLLATE utf8_bin ";
$ret .=
"CHARACTER SET utf8 COLLATE utf8_bin ";
$ret .=
"CHARACTER SET utf8 COLLATE utf8_bin ";
case "tinyint":
// <pk-07-10-30>
if (!isset
($dbDesc['LEN']))
} elseif ((intval($dbDesc['LEN']) >
4) ||
(!intval($dbDesc['LEN']))) {
$ret=
" TINYINT({$dbDesc['LEN']}) ";
if ((intval($dbDesc['LEN']) >
0) &&
(intval($dbDesc['LEN']) <
32)) { // <pk-05-11-09 />
$ret.=
"(".
intval($dbDesc['LEN']) .
") ";
case "double":
// <pk-06-05-09 />
if (isset
($dbDesc['NULL']) &&
(!$dbDesc['NULL'])) {
if ($dbDesc['DEFAULT']) {
if ($dbDesc['AUTO_INCREMENT']) {
if ($dbDesc['PRIMARY_KEY']) {
* adds a column to a table
public function addColumn($aTable,$colName,&$dbDesc,$debug=
False)
$cmd =
"ALTER TABLE $aTable ADD ".
trim($colName);
if ($debug) echoDebugLine(__FILE__
,__LINE__
,"<blockquote><b>addColumn</b> CMD:$cmd</blockquote>");
ocsp_logError(__FILE__
,__LINE__
,"could not get column def",E_WARNING);
ocsp_logError(__FILE__
,__LINE__
,"table $aTable does not exist",E_WARNING);
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* returns the where clause for a select
* @param array $conditions
if ($conditions &&
sizeof($conditions))
foreach($conditions as $str_col =>
$m_val)
* returns $aValue with slashes to use to create query strings
* @version pk-05-07-05 mysql_real_escape_string added
* @version pk-06-09-11 strval added
* returns a password command $aValue
* returns the db NULL statement for NULL values
* returns the db NOW() statement for date/time values
* returns the db IFNULL/nvl statement
* returns a Date object in string representation
* if $aDateObj is NULL $this->qs_getNullStmt() is returned
* if $aDateObj in not an object $aDataObj is retured with or without slashes
* @param OCSP_DATE $aDateObj
* @param boolean $slashed use slashes
* @version pk-06-08-08 sprintf as mktime returns on some (32bit) systems wrong values if the year is greater then 2037
* @version pk-07-10-01 no need to require date class as it passed within a parameter
if ($aDateObj->isNULL()) return "NULL";
if ($slashed) $slashes=
"'"; else $slashes=
"";
$s_date=
sprintf("%04d-%02d-%02d",$aDateObj->getYear(),$aDateObj->getMonth(),$aDateObj->getDay());
$s_time=
sprintf("%02d:%02d:%02d",$aDateObj->getHour(),$aDateObj->getMinutes(),$aDateObj->getSeconds());
return $slashes.
$s_date.
" ".
$s_time.
$slashes;
* returns a sql statement for use in search
* @param string $searchStr
* @param boolean $toUpper convert the searchStr to upper cases or leave it as is
* @param boolean $inline enclose the searchStr in placeholders (%search%)
public function qs_getLikeStmt($searchStr,$toUpper=
False,$inline=
True,$debug=
False) {
if ($debug) echoDebug(__FILE__
,"<p><b>DB_mySQL::qs_getLikeStmt($searchStr)</b> (".
get_class($this).
"</p>");
// first trim the searchStr
$searchStr=
trim($searchStr);
// replace all special chars
$searchStr=
preg_replace('/[^A-Za-z0-9_\-\.]/i', "%", $searchStr);
$searchStr=
"%".
$searchStr.
"%";
* returns WHERE col IN($valArr)
* @param boolean $valuesAreString
$str_ret=
" ".
$col.
" IN (";
foreach($valArr as $m_val)
$str_val=
strval($m_val); // ensure we have a string
//echoDebugLine(__FILE__,__LINE__,"adding value: $str_val");
if (strlen($str_val) >
0) // <pk-07-08-20 /> bugfix
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* returns the linux timestamp (mktime) of a date column
* @param stirng $aDateVal
if (empty($aDateVal) ||
(substr($aDateVal,0,4)==
"0000"))
* @deprecated since pk-10-03-21
* @todo delete function when sure that it is not used
Documentation generated on Thu, 08 Jan 2009 17:45:33 +0100 by phpDocumentor 1.4.0a2