I have a php script, test.php that has the contents
<?php
require_once("classes/user.php");
echo "test";
?>
and here is the contents of user.php
<?php
class User {
private $data = array();
public function __set($name, $value) {
$this->data[$name] = $value;
}
public function __get($name) {
if (array_key_exists($name, $this->data)) {
return $this->data[$name];
}
$trace = debug_backtrace();
trigger_error(
'Undefined property via __get(): ' . $name .
' in ' . $trace[0]['file'] .
' on line ' . $trace[0]['line'],
E_USER_NOTICE);
return null;
}
public function __isset($name) {
return isset($this->data[$name]);
}
public function __unset($name) {
unset($this->data[$name]);
}
public __construct($param) {
if(is_array($param)) $this->create($param);
else $this->id($param);
}
private id($id) { //select from database
require_once('config.php');
$pdo = new PDOConfig();
$sql = "SELECT * FROM users WHERE `id` = :id";
$q = $pdo->prepare($sql);
$q->execute(array(":id"=>$id));
$resp = $q->fetchAll();
foreach ($resp as $row) {
foreach ($row as $key=>$value) {
if(!is_int($key))
$this->data[$key] = html_entity_decode($value, ENT_QUOTES);
}
}
$pdo = null;
unset($pdo);
}
private create($arr) { //create new item from values in array and insert to db
}
public delete() {
$this->life = 0;
//update database "life" here
}
/* ##################################### */
/* !Functions */
/* ##################################### */
public projects($extra = null) {
$projects = array();
require_once('project.php');
$pdo = new PDOConfig();
$sql = "SELECT * FROM ---- WHERE `000` = :aaa";
if($extra) $sql .= " " . $extra;
$q = $pdo->prepare($sql);
$q->execute(array(":aaa"=>$this->id));
$resp = $q->fetchAll();
foreach ($resp as $row) {
$project = new Project($row['id']);
$projects[] = $project;
$project = null;
unset($project);
}
return $projects;
}
}
?>
and test is never printed, and on chrome the page doesn't load at all
The website encountered an error while retrieving http://example.com/test.php. It may be down for maintenance or configured incorrectly.
I can't figure this out for the life of me. Thanks it advance
You have a syntax error in the declaration of your __construct() method :
public __construct($param) {
if(is_array($param)) $this->create($param);
else $this->id($param);
}
You need to use the function keyword, like this :
public function __construct($param) {
if(is_array($param)) $this->create($param);
else $this->id($param);
}
To help find those errors, on your development computer, you should enable :
error_reporting
and display_errors
In fact, I just copy-pasted your code to a .php file and ran it -- and got a nice
Parse error: syntax error, unexpected T_STRING, expecting T_VARIABLE
in /home/.../temp/temp.php on line 39
Related
I have problem with save data in mysql.
I have such a class to connect with databases:
class Db
{
private $_hostname;
private $_database;
private $_username;
private $_password;
private $_port;
private $_pdo;
private $_sQuery;
private $_bConnected = false;
private $_parameters;
private $_config;
private $_psException;
public function __construct()
{
$this->_config = Registry::register("Core\Utilities\Config");
$this->_psException = new PsException();
$this->_hostname = $this->_config->db_host;
$this->_database = $this->_config->db_db;
$this->_username = $this->_config->db_user;
$this->_password = $this->_config->db_pass;
$this->_port = $this->_config->db_port;
$this->Connect($this->_hostname, $this->_database, $this->_username, $this->_password, $this->_port);
$this->_parameters = array();
}
private function Connect($hostname, $database, $username, $password, $port)
{
try {
$options = array(\PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'");
$this->_pdo = new \PDO("mysql:host={$hostname};dbname={$database};port={$port};charset=utf8", $username, $password, $options);
$this->_pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
$this->_pdo->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_ASSOC);
$this->_pdo->setAttribute(\PDO::ATTR_EMULATE_PREPARES, true);
$this->_pdo->query('SET NAMES utf8');
$this->_bConnected = true;
} catch (PDOException $ex) {
$this->_psException->registerError("Failed to connect to the database: " . $ex->getMessage());
} catch (Exception $e) {
$this->_psException->registerError("Failed to connect to the database: " . $e->getCode() . "." . $e->getMessage());
}
}
public function CloseConnection()
{
$this->_pdo = null;
}
private function Init($query, $parameters = "")
{
if (!$this->_bConnected) {
$this->Connect();
}
try {
$this->_sQuery = $this->_pdo->prepare($query);
$this->bindMore($parameters);
if (!empty($this->_parameters)) {
foreach ($this->_parameters as $param) {
$parameters = explode("\x7F", $param);
$this->_sQuery->bindParam($parameters[0], $parameters[1]);
}
}
$this->success = $this->_sQuery->execute();
} catch (PDOException $e) {
$this->ExceptionLog($e->getMessage(), $query);
}
$this->_parameters = array();
}
public function bind($para, $value)
{
$this->_parameters[sizeof($this->_parameters)] = ":" . $para . "\x7F" . ($value);
}
public function bindMore($parray)
{
if (empty($this->_parameters) && is_array($parray)) {
$columns = array_keys($parray);
foreach ($columns as $i => &$column) {
$this->bind($column, $parray[$column]);
}
}
}
public function query($query, $params = null, $fetchmode = \PDO::FETCH_ASSOC)
{
$query = trim($query);
$this->Init($query, $params);
$rawStatement = explode(" ", $query);
$statement = strtolower($rawStatement[0]);
if ($statement === 'select' || $statement === 'show') {
return $this->_sQuery->fetchAll($fetchmode);
} elseif ($statement === 'insert' || $statement === 'update' || $statement === 'delete') {
return $this->_sQuery->rowCount();
} else {
return null;
}
}
public function lastInsertId()
{
return $this->_pdo->lastInsertId();
}
public function column($query, $params = null)
{
$this->Init($query, $params);
$Columns = $this->_sQuery->fetchAll(\PDO::FETCH_NUM);
$column = null;
foreach ($Columns as $cells) {
$column[] = $cells[0];
}
return $column;
}
public function row($query, $params = null, $fetchmode = \PDO::FETCH_ASSOC)
{
$this->Init($query, $params);
return $this->_sQuery->fetch($fetchmode);
}
public function single($query, $params = null)
{
$this->Init($query, $params);
return $this->_sQuery->fetchColumn();
}
private function ExceptionLog($message, $sql = "")
{
$message .= 'Unhandled Exception. $message';
if (!empty($sql)) {
$message .= "\r\nQuery SQL : " . $sql;
}
$this->_psException->registerError($message);
}
}
and the method to write:
$queryValue["enable"] = $dataValues['enable'];
$queryValue["number"] = $dataValues['number'];
$queryValue["description"] = $dataValues['description'];
$queryValue["date"] = $dataValues['date'];
$queryValue["visible_on_the_front"] = $dataValues['visible_on_the_front'];
$queryValue["id_category_page"] = $dataValues['id_category_page'];
$queryValue["visible_on_the_front2"] = $dataValues['visible_on_the_front2'];
$this->_db->query("INSERT INTO psGalleryCategories (visible_on_the_front2, id_category_page, visible_on_the_front, date, description, enable, number) VALUES (:visible_on_the_front2, :id_category_page, :visible_on_the_front, :date, :description, :enable, :number);", $queryValue);
When he writes such a string of characters:
'';fwefewfpew'f'wef'wefew.''fewvdsniu*&&^&^#^7ef125e2'""''
I have error:
Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'f'wef'wefew.''fewvdsniu*&&^&^#^7ef125e2''' at line 1 in /Applications/XAMPP/xamppfiles/htdocs/um/apps/core/utilities/DbClass.php:78 Stack trace: #0 /Applications/XAMPP/xamppfiles/htdocs/um/apps/core/utilities/DbClass.php(78): PDOStatement->execute() #1 /Applications/XAMPP/xamppfiles/htdocs/um/apps/core/utilities/DbClass.php(139): Core\Utilities\Db->Init('SELECT COUNT(ti...', NULL) #2 /Applications/XAMPP/xamppfiles/htdocs/um/apps/core/models/ModelClass.php(24): Core\Utilities\Db->row('SELECT COUNT(ti...') #3 /Applications/XAMPP/xamppfiles/htdocs/um/apps/backend/models/GalleryModel.php(230): Core\Models\Model->createSeoUrl(''';fwefewfpew'f...', 'title_pl', 'psGalleryCatego...') #4 /Applications/XAMPP/xamppfiles/htdocs/um/apps/backend/controllers/GalleryList.php(14 in /Applications/XAMPP/xamppfiles/htdocs/um/apps/core/utilities/DbClass.php on line 78
How to fix this error?
I do not have any problems with normal string. Problem is with combination ',/, "", etc (special characters).
Please help me.
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?
i'm working on admin panel form and i have a problem in connect form page to mysql .. i made table name : main_settigns and i'm working with MVC .. this is the form controller :-
enter code here
<?php
if(isset($_POST['submit']) && $_POST['submit'] == "Update")
{
$mainsettings['site_name'] = $_POST['site_name'];
$mainsettings['site_url'] = $_POST['site_url'];
$mainsettings['site_desc'] = $_POST['site_desc'];
$mainsettings['site_email'] = $_POST['site_email'];
$mainsettings['site_tags'] = $_POST['site_tags'];
$mainsettings['site_homapanel'] = $_POST['site_homapanel'];
$mainsettings['fb'] = $_POST['fb'];
$mainsettings['tw'] = $_POST['tw'];
$mainsettings['yt'] = $_POST['yt'];
$mainsettings['username'] = $_POST['username'];
try {
include 'models/Arageek.php';
include 'models/Add.php';
$addmMainSettings = new Add($mainsettings, "main_settigns");
if($addmMainSettings == TRUE)
{
echo 'successfully Added';
}
}
catch (Exception $exc)
{
echo $exc->getMessage();
}
}
else
{
try {
include 'models/Arageek.php';
include 'models/Display.php';
$data = new Display("main_settigns");
$displayData = $data->getData();
} catch (Exception $exc)
{
echo $exc->getMessage();
}
include 'views/v_mainSettings.php';
}
?>
this is the model page :-
enter code here
<?php
/* add class
* insert the data into mysql database
* #author Dev.Yasser
*/
class Add extends Arageek
{
private $data;
private $tablename;
private $cxn;
public function __construct($data, $tablename)
{
if(is_array($data))
{
$this->data = $data;
$this->tablename = $tablename;
}
else
{
throw new Exception("Error: the data must be in an array .");
}
$this->connectToDB();
$this->AddData($this->data);
$this->close();
}
// insert the data into the table
function AddData($data)
{
foreach ($data as $key=> $value)
{
$keys[] = $key;
$values[] = $value;
}
$tblKeys = implode($keys, ",");
$dataValues = '"'. implode($values, '","') .'"';
$query = "INSERT INTO $this->tablename ($tblKeys) VALUES ($dataValues)";
if($sql = mysql_query($query))
{
return TRUE;
}
else {
throw new Exception("Error: Can not excute the query");
return FALSE;
}
}
}
?>
and the parent class :-
enter code here
<?php
class Arageek {
private $cxn;
function connectToDB()
{
include 'models/Database.php';
$vars = "include/vars.php";
$this->cxn=new Database($vars);
}
function close()
{
$this->cxn->close();
}
}
?>
the result after submit the form is : "Error: Can not excute the query"
I'm working on a project which is using Unit of work design pattern. It includes Storage,EntityCollection,..... Code of unit of work includes PDO Adapter code file. But the adapter is not complete for running queries. I have found the files from somewhere.
I can't build queries what I want. Every time I'm writing code I faces to many problems related query. So can you please help me to make it more flexible... For example i want to run like : $db->select()->where('id>:id')->andWhere('')->orWHere()->orderBy()->groupBy()->having()->fetch()/fetchOne(); or similar to it.
<?php
namespace D\Adapter;
class PdoAdapter implements \D\DB\DatabaseInterface {
protected $config = array();
protected $database;
protected $connection;
protected $statement;
protected $fetchMode = \PDO::FETCH_ASSOC;
public function __construct($dsn, $username = null, $password = null, array $driverOptions = array()) {
$this->config = compact("dsn", "username", "password", "driverOptions");
$this->database = $driverOptions['db_name'];
}
public function getStatement() {
if ($this->statement === null) {
throw new \PDOException(
"There is no PDOStatement object for use.");
}
return $this->statement;
}
public function connect() {
// if there is a PDO object already, return early
if ($this->connection) {
return;
}
try {
$this->connection = new \PDO(
$this->config["dsn"], $this->config["username"], $this->config["password"], $this->config["driverOptions"]);
$this->connection->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
$this->connection->setAttribute(
\PDO::ATTR_EMULATE_PREPARES, false);
} catch (\PDOException $e) {
throw new \RunTimeException($e->getMessage());
}
}
public function disconnect() {
$this->connection = null;
}
public function prepare($sql, array $options = array()) {
$this->connect();
try {
$this->statement = $this->connection->prepare($sql, $options);
return $this;
} catch (\PDOException $e) {
throw new \RunTimeException($e->getMessage());
}
}
public function execute(array $parameters = array()) {
try {
$this->getStatement()->execute($parameters);
return $this;
} catch (\PDOException $e) {
throw new \RunTimeException($e->getMessage());
}
}
public function countAffectedRows() {
try {
return $this->getStatement()->rowCount();
} catch (\PDOException $e) {
throw new \RunTimeException($e->getMessage());
}
}
/**
* countAffectedRows iin Alias
*/
public function count() {
try {
return $this->getStatement()->rowCount();
} catch (\PDOException $e) {
throw new \RunTimeException($e->getMessage());
}
}
public function getLastInsertId($name = null) {
$this->connect();
return $this->connection->lastInsertId($name);
}
public function fetch($fetchStyle = null, $cursorOrientation = null, $cursorOffset = null) {
if ($fetchStyle === null) {
$fetchStyle = $this->fetchMode;
}
try {
return $this->getStatement()->fetch($fetchStyle, $cursorOrientation, $cursorOffset);
} catch (\PDOException $e) {
throw new \RunTimeException($e->getMessage());
}
}
public function fetchAll($fetchStyle = null, $column = 0) {
if ($fetchStyle === null) {
$fetchStyle = $this->fetchMode;
}
try {
return $fetchStyle === \PDO::FETCH_COLUMN ? $this->getStatement()->fetchAll($fetchStyle, $column) : $this->getStatement()->fetchAll($fetchStyle);
} catch (\PDOException $e) {
throw new \RunTimeException($e->getMessage());
}
}
public function select($table, $bind = array(), $where = "", $options = array()) {
if (count($bind) > 0) {
foreach ($bind as $col => $value) {
unset($bind[$col]);
$bind[":" . $col] = $value;
}
}
if (isset($options['fields'])) {
$fields = $options['fields'];
} else {
$fields = '*';
}
$sql = "SELECT " . $fields . " FROM " . $table . " ";
if (strlen($where) > 2) {
$sql .= "WHERE " . $where;
}
// set_flash($sql);
$this->prepare($sql)
->execute($bind);
return $this;
}
public function query($sql, array $bind = array()) {
if (is_array($bind)) {
foreach ($bind as $col => $value) {
unset($bind[$col]);
$bind[":" . $col] = $value;
}
}
$this->prepare($sql)
->execute($bind);
return $this;
}
public function insert($table, array $bind) {
$cols = implode(", ", array_keys($bind));
$values = implode(", :", array_keys($bind));
foreach ($bind as $col => $value) {
unset($bind[$col]);
$bind[":" . $col] = $value;
}
$sql = "INSERT INTO " . $table
. " (" . $cols . ") VALUES (:" . $values . ")";
return (int) $this->prepare($sql)
->execute($bind)
->getLastInsertId();
}
public function update($table, array $bind, $where = "") {
$set = array();
foreach ($bind as $col => $value) {
unset($bind[$col]);
$bind[":" . $col] = $value;
$set[] = $col . " = :" . $col;
}
$sql = "UPDATE " . $table . " SET " . implode(", ", $set)
. (($where) ? " WHERE " . $where : " ");
return $this->prepare($sql)
->execute($bind)
->countAffectedRows();
}
public function delete($table, $where = "") {
$sql = "DELETE FROM " . $table . (($where) ? " WHERE " . $where : " ");
return $this->prepare($sql)
->execute()
->countAffectedRows();
}
public function fetchAllTables() {
$sql = "SHOW TABLES FROM " . $this->database;
$this->prepare($sql)
->execute();
return $this;
}
public function fetchAllFields($table) {
$sql = "SHOW FIELDS FROM " . $table;
$this->prepare($sql)
->execute();
return $this;
}
}
---FULL code is here---
https://github.com/batmunkhcom/mbm/tree/master/src/D
First of all the concern of an UnitOfWork Pattern is to track everything you do during a business transaction that can affect the database. After transactions, it figures out everything that needs to be done to alter the database as a result of your work. Your class has other concerns.
It looks like a godclass (antipattern). It has more than one responsibility: Connection, PeparedStatement, Execution, and other helpers. Its quite difficult to scale and maintain. Try to split all responsibilities to different classes in SOLID way with corresponding design pattern.
Your idea faced in your code is already done by other frameworks. Its very hard work to implement it again. For example you can try Doctrine ORM/DBAL Framework.
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');
}
}
}