Migrate PHP code from MySQL to MS SQL Server - php

I want to migrate a php/mysql script to php/sql-server. The script code isn't mine, I tried to hack it by replacing mysqli_connect() with sqlsrv_connect(), but it's not working.
How I can migrate the script?
the script source code : https://github.com/fixwa/BlackFramework/tree/master/Lib/xcrud
Below is the database configuration code :
/** Database driver; f0ska xCRUD v.1.6.20; 06/2014 */
class Xcrud_db
{
private static $_instance = array();
private $connect;
public $result;
private $dbhost;
private $dbuser;
private $dbpass;
private $dbname;
private $dbencoding;
private $magic_quotes;
public static function get_instance($params = false)
{
if (is_array($params))
{
list($dbuser, $dbpass, $dbname, $dbhost, $dbencoding) = $params;
$instance_name = sha1($dbuser . $dbpass . $dbname . $dbhost . $dbencoding);
}
else
{
$instance_name = 'db_instance_default';
}
if (!isset(self::$_instance[$instance_name]) or null === self::$_instance[$instance_name])
{
if (!is_array($params))
{
$dbuser = Xcrud_config::$dbuser;
$dbpass = Xcrud_config::$dbpass;
$dbname = Xcrud_config::$dbname;
$dbhost = Xcrud_config::$dbhost;
$dbencoding = Xcrud_config::$dbencoding;
}
self::$_instance[$instance_name] = new self($dbuser, $dbpass, $dbname, $dbhost, $dbencoding);
}
return self::$_instance[$instance_name];
}
private function __construct($dbuser, $dbpass, $dbname, $dbhost, $dbencoding)
{
$this->magic_quotes = get_magic_quotes_runtime();
if (strpos($dbhost, ':') !== false)
{
list($host, $port) = explode(':', $dbhost, 2);
preg_match('/^([0-9]*)([^0-9]*.*)$/', $port, $socks);
$this->connect = mysqli_connect($host, $dbuser, $dbpass, $dbname, $socks[1] ? $socks[1] : null, $socks[2] ? $socks[2] : null);
}
else
$this->connect = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if (!$this->connect)
$this->error('Connection error. Can not connect to database');
$this->connect->set_charset($dbencoding);
if ($this->connect->error)
$this->error($this->connect->error);
if (Xcrud_config::$db_time_zone)
$this->connect->query('SET time_zone = \'' . Xcrud_config::$db_time_zone . '\'');
}
public function query($query = '')
{
$this->result = $this->connect->query($query, MYSQLI_USE_RESULT);
//echo '<pre>' . $query . '</pre>';
if ($this->connect->error)
$this->error($this->connect->error . '<pre>' . $query . '</pre>');
return $this->connect->affected_rows;
}
public function insert_id()
{
return $this->connect->insert_id;
}
public function result()
{
$out = array();
if ($this->result)
{
while ($obj = $this->result->fetch_assoc())
{
$out[] = $obj;
}
$this->result->free();
}
return $out;
}
public function row()
{
$obj = $this->result->fetch_assoc();
$this->result->free();
return $obj;
}
public function escape($val, $not_qu = false, $type = false, $null = false, $bit = false)
{
if ($type)
{
switch ($type)
{
case 'bool':
if ($bit)
{
return (int)$val ? 'b\'1\'' : 'b\'0\'';
}
return (int)$val ? 1 : ($null ? 'NULL' : 0);
break;
case 'int':
$val = preg_replace('/[^0-9\-]/', '', $val);
if ($val === '')
{
if ($null)
{
return 'NULL';
}
else
{
$val = 0;
}
}
if ($bit)
{
return 'b\'' . $val . '\'';
}
return $val;
break;
case 'float':
if ($val === '')
{
if ($null)
{
return 'NULL';
}
else
{
$val = 0;
}
}
return '\'' . $val . '\'';
break;
default:
if (trim($val) == '')
{
if ($null)
{
return 'NULL';
}
else
{
return '\'\'';
}
}
else
{
if ($type == 'point')
{
$val = preg_replace('[^0-9\.\,\-]', '', $val);
}
//return '\'' . ($this->magic_quotes ? (string )$val : $this->connect->real_escape_string((string )$val)) . '\'';
}
break;
}
}
if ($not_qu)
return $this->magic_quotes ? (string )$val : $this->connect->real_escape_string((string )$val);
return '\'' . ($this->magic_quotes ? (string )$val : $this->connect->real_escape_string((string )$val)) . '\'';
}
public function escape_like($val, $pattern = array('%', '%'))
{
if (is_int($val))
return '\'' . $pattern[0] . (int)$val . $pattern[1] . '\'';
if ($val == '')
{
return '\'\'';
}
else
{
return '\'' . $pattern[0] . ($this->magic_quotes ? (string )$val : $this->connect->real_escape_string((string )$val)) .
$pattern[1] . '\'';
}
}
private function error($text = 'Error!')
{
exit('<div class="xcrud-error" style="position:relative;line-height:1.25;padding:15px;color:#BA0303;margin:10px;border:1px solid #BA0303;border-radius:4px;font-family:Arial,sans-serif;background:#FFB5B5;box-shadow:inset 0 0 80px #E58989;">
<span style="position:absolute;font-size:10px;bottom:3px;right:5px;">xCRUD</span>' . $text . '</div>');
}
}
My hacked code :
private function __construct($dbname, $dbhost, $dbencoding)
{
$this->magic_quotes = get_magic_quotes_runtime();
if (strpos($dbhost, ':') !== false)
{
list($host, $port) = explode(':', $dbhost, 2);
preg_match('/^([0-9]*)([^0-9]*.*)$/', $port, $socks);
$this->connect = sqlsrv_connect($host,$dbname, $socks[1] ? $socks[1] : null, $socks[2] ? $socks[2] : null);
}
else
$this->connect = sqlsrv_connect($dbhost, $dbname);
if (!$this->connect)
$this->error('Connection error. Can not connect to database');
$this->connect->set_charset($dbencoding);
if ($this->connect->error)
$this->error($this->connect->error);
if (Xcrud_config::$db_time_zone)
$this->connect->query('SET time_zone = \'' . Xcrud_config::$db_time_zone . '\'');
}
In config file :
> // default connection
> public static $dbname = array( "Database"=>"crud1");
> > public static $dbhost = '.\sqlexpress';

You should use PDO, specially if you hope for a better future for your application or website, but you can still use sqlsrv_* functions if you want. Whatever you do, make sure you replace all function and provide the right parameters.
Let's see if you want to use SQLSRV Functions (which I don't recommend but I feel this is what you want); You need to change all mysqli_* functions with their sqlsrv_* counter part, and again, provide the right parameter in the right form:
Example
In the constructor, you have:
$this->connect = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
That should be replaced with:
$this->connect = sqlsrv_connect($dbhost, array( 'Database'=>$dbName, 'UID'=>$dbuser, 'PWD'=>$dbpass));
You see that mysqli_connect was called with 4 parameters (all strings), but sqlsrv_connect was called with only 2, (a string and an array).

Related

Create my oracle oci class in php. But data show 1 first record only

This code from my PHP Project.
and create oracle connection class.
modified from mysql connection class(work fine).
class databaseOracle
{
public $oci;
public $connected = false;
public $parameters;
public $result;
function __construct($host, $dbPort, $dbName, $userDB, $passwordDB)
{
try {
$ociDB = "(DESCRIPTION=(ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = " . $host . ")(PORT = " . $dbPort . ")))(CONNECT_DATA=(SID=" . $dbName . ")))";
$this->oci = oci_connect($userDB, $passwordDB, $ociDB, 'AL32UTF8');
if (!$this->oci) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
echo "Database oracle connection Failed.</br>";
exit();
} else {
echo "Database oracle connection success.</br>";
}
} catch (EngineExcpetion $e) {
echo "Error : " . $e->getMessage() . "</br>";
}
// exit();
}
public function bind($para, $value)
{
$this->parameters[count($this->parameters)] = ":" . $para . "\x7F" . $value;
}
public function bindParams($parray)
{
if (empty($this->parameters) && is_array($parray)) {
$columns = array_keys($parray);
foreach ($columns as $i => &$column) {
$this->bind($column, $parray[$column]);
}
}
}
public function queryString($showQuery = 0, $query = "", $parameters = "")
{
$this->result = null;
if ($showQuery == 1) {
require_once('SQLFormatter.php');
echo SqlFormatter::format($query);
var_dump($parameters);
}
$this->result = oci_parse($this->oci, $query);
# Add parameters to the parameter array
$this->bindParams($parameters);
# Bind parameters
if (!empty($this->parameters)) {
foreach ($this->parameters as $param) {
$parameters = explode("\x7F", $param);
oci_bind_by_name($this->result, $parameters[0], $parameters[1]);
}
}
oci_execute($this->result);
$r = oci_fetch_array($this->result, OCI_ASSOC + OCI_RETURN_LOBS + OCI_RETURN_NULLS);
$this->parameters = array();
return $r;
}
}
$oracleDB = new databaseOracle($ociHost, $ociPort, $ociDB, $ociUsername, $ociPassword);
$query = $oracleDB->queryString(0,"SELECT * from SOME_TABLE where CREATED_BY = :created FETCH NEXT 50 ROWS ONLY",array("created" => "2"));
print_r($query);
my problem
i'm create class of oracle connection. modify from mysql connection class.
it's can query and read record from oracle database. example 50 record
but array result of query show first row only.

Fixing max_user_connections in PHP class using PDO

I have been adapting an older abstraction layer to use PDO but I am running into user x has more than 'max_user_connections' active connections SQLSTATE[HY000] [1203] errors when looping through large sets. I have been reading on http://php.net/manual/en/pdo.connections.php but all of my attempts to unset the $dbh from within the loops result in errors from having ended the connection.
Base class looks like
class DB {
public $pdo;
private $host = DB_HOST;
private $user = DB_USER;
private $pass = DB_PASS;
private $dbname = DB_NAME;
public function __construct()
{
$this->connect();
}
private function connect()
{
$options = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
try {
$this->pdo = new PDO("mysql:host=$this->host;dbname=$this->dbname;charset=utf8;", $this->user, $this->pass, $options);
} catch(PDOException $e) {
echo $e->getMessage();
}
}
public function __sleep()
{
return array('dsn', 'username', 'password');
}
public function __wakeup()
{
$this->connect();
}
public function __destruct()
{
$this->connection = null;
$this->pdo = null;
unset($this->pdo);
}
// CRUD methods follow including
function retrieve($where, $groupBy='', $order_by='') {
$query = "SELECT * FROM `$this->table` $where $groupBy $order_by";
$q = $this->pdo->prepare($query);
$q->execute();
$result = $q->fetchAll(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE,get_class($this));
// was $result = $q->fetchAll(PDO::FETCH_CLASS,get_class($this));
$this->query_log($query);
$q = null;
if ($result == 'NULL') {
return false;
} else {
return $result;
}
} // retrieve()
And an example that has the errors would be
if (in_array($_GET['type'], $types)) {
$type = $_GET['type'];
$rsObj = new ReservedSlug;
if ($type == 'artist') {
$obj = new CalendarArtist;
$slugfield = 'urlSlug';
$namefield = 'name';
} else if ($type == 'event') {
$obj = new CalendarEvent;
$slugfield = 'urlSlug';
$namefield = 'name';
} else if ($type == 'location') {
$obj = new Location;
$slugfield = 'UrlSlug';
$namefield = 'LocationName1';
}
$needslug = $obj->retrieve("TRIM(`$namefield`) != '' AND (`$slugfield` = '' OR `$slugfield` IS NULL) LIMIT 0,400");
if ($needslug) {
foreach ($needslug as $ns) {
$testslug = slugify($ns->$namefield);
list($reserved) = $rsObj->retrieve("`slug` = '$testslug' AND `type` = '$type'");
if (!$reserved) {
list($test) = $obj->retrieve("`$slugfield` = '$testslug'");
if ($test) {
for ($i = 2; $i < 26; $i++) {
list($test) = $obj->retrieve("`$slugfield` = '$testslug-$i'");
if (!$test) {
$slug = $testslug . '-' . $i;
}
}
} else { // not found in table
$slug = $testslug;
}
} else { // was reserved
$slug = false;
}
echo $ns->$namefield . " gets $slug<p>";
} // foreach needslug
} // if needslug
} // type found in array
So I need to understand how to not create new connections when an active connection is available and how to properly __destruct() these child objects. Where am I going wrong?

php with pdo, create dynamic database connection

I create connection with this statement
dbh = new PDO('mysql:host=localhost;dbname=mydb;port=3306;connect_timeout=15', 'root', '');
But in my application users capable to change data sources so I need to create current database connection with server informations user posted, I try this:
dbh = new PDO('sqlsrv:server=' + $result["servername"] + ';dbname=' + $result["dbname"] + ';port=3306;connect_timeout=15', '' + $result["user"] + '', '' + $result["password"] + '');`
But it failed. Even I tried the simple code examples got documents it fails for that too.. Whats with it and how can I make it ?
At first, you cant merge strings with '+'. you must use '.' and you need to create new PDO connection object(or set it existing) for each database connection here I share parts of my code doing this:
private function __construct()
{
//default database connection
$this->dbh = new PDO('mysql:host=localhost;dbname=webfilter;port=3306;connect_timeout=15', 'root', '');
$this->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->dbh->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$this->directed = false;
$this->resultBool = true;
}
public static function getConnection()
{
$sqlstring = "select * from datasources WHERE ACTIVE =1";
if (!isset(self::$instance))
{
$object = __CLASS__;
self::$instance = new $object;
}
if (true) {
$request = self::$instance->dbh->prepare($sqlstring);
if ($request->execute()) {
if ($result = $request->fetch(PDO::FETCH_ASSOC)) {
if ($result["SOFTWARE"] == "mysql") {
self::$instance->dbh = null;
self::$instance->connectedDbName = "mysql(" . $result["DATABASENAME"] . ")";
self::$instance->dbh = new PDO('mysql:host=' . $result["SERVERADDRESS"] . ';dbname=' . $result["DATABASENAME"] . ';port=3306;connect_timeout=15', '' . $result["USERNAME"] . '', '' . $result["PASSWORD"] . '');
self::$instance->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
self::$instance->directed = true;
self::$instance->resultBool = true;
} else if ($result["SOFTWARE"] == "mssql") {
self::$instance->dbh = null;//close the existing connection
self::$instance->connectedDbName = "mssql(" . $result["DATABASENAME"] . ")";
self::$instance->dbh = new PDO('sqlsrv:server=' . $result["SERVERADDRESS"] . ';Database=' . $result["DATABASENAME"] . '', '' . $result["USERNAME"] . '', '' . $result["PASSWORD"] . '');
self::$instance->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
self::$instance->dbh->query("use " . $result["DATABASENAME"]);
self::$instance->directed = true;
self::$instance->resultBool = true;
} else if ($result["SOFTWARE"] == "oracle") {
self::$instance->connectedDbName = "oracle(" . $result["DATABASENAME"] . ")";
self::$instance->dbh = new PDO('odbc:DRIVER=FreeTDS;server=localhost;Database=Dbname', 'username', '!123qwe');
}
self::$instance->resultBool = true;
$temp = self::$instance->dbh->query("select DEVICEID from ethernet LIMIT 1");
self::$instance->setDeviceid($temp->fetchColumn());
return self::$instance;
}
self::$instance->connectedDbName = "default";
$temp = self::$instance->dbh->query("select DEVICEID from ethernet LIMIT 1");
self::$instance->setDeviceid($temp->fetchColumn());
return self::$instance;
}
}
self::$instance->connectedDbName = "default";
return self::$instance;
}
public function getConnectionStatusMessage()
{
if ($this->resultBool) {
return "Connection Successfull" . $this->connectedDbName;
} else {
return "Connection Failed:" . $this->resultString;
}
}
$dbh = new PDO('sqlsrv:server=' . $result["servername"] . ';dbname=' . $result["dbname"] . ';port=3306;connect_timeout=15', $result["user"], $result["password"]);

store multiple pdo connections in an array

so i have been trying to debug this issue myself for a few days now and i can't seem to figure out why i'm not getting the results I expect.
My code is rather complex and for a DB connection to be establish it spans across 3 Classes and one config file.
but basically my end usage ends up being
$this->db('test')->query('SELECT * FROM test1');
this establishes a connection to my database by the alias of test the query returns results so i'm good so far.
now my issue is when i try to make a new PDO object.
$this->db('test2')->query('SELECT * FROM test2');
this returns nothing because there is not table called test2 in my test1 object.
but if I do this
$this->db('test2')->query('SELECT * FROM test1');
now this returns the same results from the first PDO object.
I have traced and tracked down every line of code to make sure that the correct parameters are being passed to my database class and that each connection is properly established to the corresponding databases.
now my question is, can you have more than one datbase pdo connection? if so is there a special flag that needs to be set in the PDO options? are my connections being cached somewhere and causing this confusion?
this is my PDO declaration in each new class object stored in my array of connections
try
{
$this->_con = new PDO(
"mysql:host=" . $host . ";
port=" . $port . ";
dbname=" . $name, $user, $pass
);
$this->_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
// TODO: push all $e methods to the developer debugger
echo "Database Error: ". $e->getMessage();
}
edit my code that uses the connection
step 1: a call to the parent class
public function __call($name, $params)
{
$class = $name . '_system_helper';
$hash = md5($class . $params);
if (class_exists($class))
{
if (!array_key_exists($hash, $this->_sys_helper))
{
if (method_exists($class, 'init'))
{
$this->_sys_helper[$hash] = call_user_func_array(array($class, 'init'), $params);
} else {
$this->_sys_helper[$hash] = call_user_func_array($class, $params);
}
}
return $this->_sys_helper[$hash];
}
return null;
}
step 2: called from the parent class
class DB_System_Helper extends Jinxup
{
private $_con = null;
public function __construct($end = null)
{
$mode = null;
$host = null;
$name = null;
$user = null;
$pass = null;
$port = null;
if (isset($this->config['database']['mode']))
{
$mode = $this->config['database']['mode'] == 'production' ? 'production' : 'development';
if (count($this->config['database'][$mode]) > 1)
{
foreach ($this->config['database'][$mode] as $key => $database)
{
if ($database['#attr']['alias'] == $end)
{
$host = $this->config['database'][$mode][$key]['host'];
$name = $this->config['database'][$mode][$key]['name'];
$user = $this->config['database'][$mode][$key]['user'];
$pass = $this->config['database'][$mode][$key]['pass'];
$port = $this->config['database'][$mode][$key]['port'];
}
}
} else {
$host = $this->config['database'][$mode]['host'];
$name = $this->config['database'][$mode]['name'];
$user = $this->config['database'][$mode]['user'];
$pass = $this->config['database'][$mode]['pass'];
$port = $this->config['database'][$mode]['port'];
}
$this->_con = new PDO_Database_Helper($host, $name, $user, $pass, $port);
} else {
echo 'No database mode specified';
}
}
public function __call($name, $param)
{
return call_user_func_array(array($this->_con, $name), $param);
}
}
step 3: called from DB_System_Helper
class PDO_Database_Helper extends Jinxup
{
private $_con = null;
private $_id = 0;
public function __construct($host, $name, $user, $pass, $port = 3306)
{
try
{
$this->_con = new PDO(
"mysql:host=" . $host . ";
port=" . $port . ";
dbname=" . $name, $user, $pass
);
$this->_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
// TODO: push all $e methods to the developer debugger
echo "Database Error: ". $e->getMessage();
}
}
[...]
}
Are you sure that the hashing you're doing is enough to "namespace" each connection in the $this->_sys_helper array?
I suspect the problem lies in the first stage.
public function __call($name, $params)
{
$class = $name . '_system_helper';
$hash = md5($class . $params);
if (class_exists($class))
{
if (!array_key_exists($hash, $this->_sys_helper))
{
if (method_exists($class, 'init'))
{
$this->_sys_helper[$hash] = call_user_func_array(array($class, 'init'), $params);
} else {
$this->_sys_helper[$hash] = call_user_func_array($class, $params);
}
}
>>>>>>>>>>>>>> are you sure this is not returning the wrong
>>>>>>>>>>>>>> connection because of how the hashing is working?
return $this->_sys_helper[$hash];
}
return null;
}

Database class design

I'm creating a web app with various classes for things like the user, Smarty template control, etc.
I already have a database class which is all well and good, but I'm concerned about the performance of it.
Currently, in another class, I'm doing $this->db = new DB() to create a local database instance, however the database class's __construct() function creates a new connection to the MySQL server every time I make a new DB() instance, which is obviously less than sensible. This means that each instance of all my different classes that uses the database class makes a connection to the server. I don't have a vast amount of classes, but I only want one per page load.
This is a stripped down sample of what I have at the moment:
// Database class used by multiple other classes
class DB {
private $dbh;
function __construct() {
$this->dbh = // PDO connection here
}
public function query($str) {
// Do a query
}
}
// Example class User
class User {
private $db; // Stores local instance of DB class.
function __construct() {
$this->db = new DB(); // Makes a new connection in DB::__construct()
}
public function login() {
$this->db->query('SELECT * FROM users');
}
}
I'm looking for the "best" or most common practice of doing this. I don't want to make 10-ish separate connections for each page load.
I want to know what the best way of using and managing a DB class in my application. My four thoughts are these:
Would using a persistent connection to the MySQL server solve this multiple connection issue for me?
Should I use a static factory class and return a DB instance instead of using new DB()?
Is the proper solution to use an entirely static class and just do DB::query() (for example) every time I reference it?
I often use multiple classes in another (so we might have class Folders which requires classes User, DB and Smarty). Is it general practice to extend each class somehow?
If you make the variable holding the connection static, then you can check if you already established a connection. Static variables are the same across all instances of the class, so you can create 100 instances that all use the same connection. You just need to reference it statically: self::$dbh instead of $this->dbh.
class DB {
private static $dbh = null;
function __construct() {
if ( is_null(self::$dbh) ) {
self::$dbh = // PDO connection here
}
}
}
I would suggest you to check the $this -> db at first and then only create it.
function __construct() {
if(!isset($this -> db) || !is_a("DB", $this -> db)) {
$this->db = new DB(); // Makes a new connection in DB::__construct()
}
}
You need to inject db connection to your class instead of creating a new connection.
// In a bootstrap file
$db = new DB();
// User.php
class User {
private $db;
function __construct($db=null) {
if (!is_null($db)) {
$this->setConnection($db);
}
}
function setConnection($db) {
$this->db = $db;
}
public function login() {
$this->db->query('SELECT * FROM users');
}
}
BTW, Zend_Registry is a good solution if you prefer it http://framework.zend.com/manual/en/zend.registry.using.html
<?php
class DBLayer {
public $prefix;
public $link_id;
public $query_result;
public $saved_queries = array();
public $num_queries = 0;
public function DBLayer() {
$db_prefix = '';
$this->prefix = $db_prefix;
if (isset($this->link_id)) {
return $this->link_id;
}
$this->link_id = #mysql_connect(DATABASE_HOST, DATABASE_USER, DATABASE_PASSWORD, true);
if ($this->link_id) {
if (#mysql_select_db(DATABASE_NAME, $this->link_id)) {
return $this->link_id;
} else {
$this->wplog("Unable to select database. Host:". DATABASE_HOST. "Database:" . DATABASE_NAME . " Error: " . mysql_error(), 'ERROR', __FILE__, __LINE__);
}
} else {
$this->wplog("Unable to connect to MySQL server. Host: " . DATABASE_HOST . " Error: " . mysql_error(), 'ERROR', __FILE__, __LINE__);
}
}
public function query($sql, $unbuffered = false) {
if(LOG){echo "<hr>$sql";}
$this->query_result = #mysql_query($sql, $this->link_id);
if ($this->query_result) {
return $this->query_result;
} else {
$msg= $sql . "<br /> Error: (" . mysql_errno() . ") " . mysql_error();
$this->wplog($msg);
}
}
public function result($query_id = 0, $row = 0) {
return ($query_id) ? #mysql_result($query_id, $row) : false;
}
public function fetch_assoc($query_id = 0) {
return ($query_id) ? #mysql_fetch_assoc($query_id) : false;
}
public function fetch_row($query_id = 0) {
return ($query_id) ? #mysql_fetch_row($query_id) : false;
}
public function num_rows($query_id = 0) {
return ($query_id) ? #mysql_num_rows($query_id) : false;
}
public function affected_rows() {
return ($this->link_id) ? #mysql_affected_rows($this->link_id) : false;
}
public function insert_id() {
return ($this->link_id) ? #mysql_insert_id($this->link_id) : false;
}
public function get_num_queries() {
return $this->num_queries;
}
public function get_saved_queries() {
return $this->saved_queries;
}
public function free_result($query_id = false) {
return ($query_id) ? #mysql_free_result($query_id) : false;
}
public function escape($str) {
if (function_exists('mysql_real_escape_string'))
return mysql_real_escape_string($str, $this->link_id);
else
return mysql_escape_string($str);
}
public function get_select($q, $onlyone=false) {
$results = array();
$r = $this->query($q);
if ($onlyone) {
return $this->fetch_assoc($r);
}
while ($l = $this->fetch_assoc($r)) {
$results[] = $l;
}
return $results;
}
public function get_error() {
return mysql_error();
}
public function close() {
if ($this->link_id) {
if ($this->query_result)
#mysql_free_result($this->query_result);
return #mysql_close($this->link_id);
}
else
return false;
}
public function auto_execute($table, $data, $type, $criteria='') {
$result = $this->get_select("desc " . $table);
if ($type == "INSERT")
$start = "insert into " . $table . " set ";
elseif ($type == "UPDATE")
$start = "update " . $table . " set ";
$sql = $start;
foreach ($result as $rst) {
foreach ($data as $key => $value) {
if ($key == $rst['Field'] and $key !== 0) {
if ((#ereg('date', $rst['Type'])) && $value == '') {
$sql = $sql . "`".$key."`" . "=NULL, ";
} elseif ((!#ereg('int', $rst['Type']))) {
$sql = $sql . "`".$key."`" . "='" . $value . "', ";
} else {
if (trim($value) != "") {
$sql = $sql . "`".$key."`" . "=" . $value . ", ";
}
}
}
}
}
if ($sql == $start)
return 0;
else {
$sql = substr($sql, 0, strlen($sql) - 2);
if ($type == "UPDATE" and !empty($criteria))
$sql = $sql . " where " . $criteria;
}
//echo $sql;exit;
if ($this->query($sql)) {
$return = $this->insert_id();
} else {
$return = 0;
}
return $return;
}
private function wplog($message) {
if(LOG==true){
$lineBreak = "\n"; // this function will NOT work on a windows server without further modification
$contents = date('Y-m-d H:i:s') . ' ' . $message. $lineBreak;
$myFile = SERVER_PATH.'/log.txt';
$fh = fopen($myFile, 'a') ;
fwrite($fh, $contents);
fclose($fh);
//SetFileContents(SERVER_PATH.'/log.txt',$contents,'a');
}
}
}

Categories