PHP - New Instance Of Class Rewriting Other Instance?
I've been looking everywhere for a solution of this but I can't find one...
Basically what I did was created a class named USER.
public class USER{ private static $USER = array(); public function __construct($U='') { // if $U is not entered (=='') then set $U to MY USER ID ($_COOKIE['user']) // do a mysql query by the ID (ala $U) and store the results to self::$USER } public function ID() { return self::$USER['id']; } }This is the code I am running... I do a user profile page that shows different properties of the USER from the database: USERNAME(),ID(),PHONE(),EMAIL(), etc. etc. // creates an instance of a different user (other than myself) $PROFILE = new USER($ID); // $ID: 26 will retrieve USERNAME: Test // create an instance of user class for myself using the cookie holding my id $ME = new USER($_COOKIE['user']) // $_COOKIE['user']: 01 will retrieve USERNAME: Monster echo($PROFILE->USERNAME()); // displays Monster echo($PROFILE->ID()); // displays 01Any idea what I am doing wrong? I would assume that $PROFILE->USERNAME() would display Test and $ME->USERNAME() would show monster. Similar TutorialsI have an existing instance of my class Database, now I want to call that instance in my Session class, how would I go about doing this? json_decode returns a stdClass Object. Is there any way where I can get instance of my class instead of the same? I mean If I json_decode the below string then it will provide me instance of stdClass and not instance of Person class {"name":"a"} How to achieve the same? Thanks in advance CSJakharia Hi All
I have not really played around with PHP in ages so I am having a hard time trying to figure out the best way to proceed. Anyhow... what I need to get done is to take a singleton pattern core database class that has a extended driver based class (ie; the type of database server the connection is connecting to), and build a new class that dynamically handles as many driver based connections that are called using a single instance. As a side note, I tried PDO but it only supports a single driver per class instance, and then each of those connections cannot not have their on set of properties that relate to each connection. Anyway, I was thinking that the best way to handle all the driver specific connections, is to hand out a 'unique hash reference' that points to an array of connection objects and the object properties. then when the client runs any sql function they pass the 'unique hash reference' which the class then returns the object and it properties that will be used by the class to call up the driver specific sql function that was requested by the client. So what do you all thing about that....
TIA stephanieT
PS...
I reason i need this is because I need to update up 25 different databases based on data stored on all the databases and not all of the database servers are of the same type, (ie; MSSQL, Oracle, MySQL, MariaDB, berkeley DB, postgres, sqlite2,3, etc, etc)! Edited January 16, 2019 by StephanieTI'm trying to make my register script check the database's IP column and compare it with the user's IP. If the User's IP equals that in the DB column, it should say "Sorry, there is already an account registered with your IP Address. Please log in.", and if there's no IP match, it should allow them to continue with registering. I've been tinkering around with this for a while and I can't seem to figure it out. Any help would be appreciated if ($_SERVER['REMOTE_ADDR'] == mysql_query("SELECT ip FROM users")) { die('Sorry, there is already an account registered with your IP Address. Please <a href="/login.php>log in.</a>'); }else{ echo ''; } I think the problem is with the mySQL query... Hey Guys. I have a shopping cart script that loops through the shopping cart session array and assigns values to the property of a class. For some weird reason the subtotal property only works when I use the self keyword. If I use the $this-> instance variable the sub total does not get assigned the subtoal price. Its just NULL.
Does anyone have any suggestions as to why it may not be working.
Below is a quick copy and paste of my code. Please be aware that some there may be some syntax mistakes as a result to copying and pasting part of my code that is relevant to this issue. Thanks!
class CoreCartFunctions { protected static $subtotal; protected $menu_item_price = NULL; public function GetMenuItem() { //self:items is the cart session array that is initilized in a construct method //Assign the values for each cart array foreach (self::$items as $menu_item_id_session) { $this->menu_item_price = getItems($this->menu_item_id,"menu_item_price")*$this->item_qty; self::$subtotal += $this->menu_item_price; //Does not work with the following ---> $this->subtotal += $this->menu_item_price; } } Hello, I'm attempting to build a Model View Controller and I've run into some issues with inheriting objects / extending classes. The application is focused around a "SuperObject", which contain instantiated libraries, helpers, controllers, models and views. I current have a Base class, which is effectively the "SuperObject". Previously I called the function GetInstance() within my model to get an instance of the SuperObject and assign it to a variable. So, $this->Instance->(The Object)->(The Method)(); However, I want to remove the need for that variable $this->Instance and just have $this->(The Object)->(TheMethod)(); And so, If you see my Controller class, libraries are instantiated as $this->Object which works perfectly. If from, within my controller I was to load the Model class. For example, $this->Loader->Library('Model'); when that model becomes instantiated, even though an extension of the Base class, I cannot use the libraries I instantiated in my controller. And of course there is a Fatal Error: Fatal error: Call to a member function UserAgent() on a non-object Code: [Select] <?php class Base { private static $Instance; public function Base() { self::$Instance =& $this; } public static function &GetInstance() { return self::$Instance; } } function &GetInstance() { return Base::GetInstance(); } Code: [Select] <?php class Controller extends Base { function Controller() { parent::Base(); $this->Initialize(); } function Initialize() { $Array = array( 'Uri', 'Loader', 'Router', 'Database', ); foreach($Array as $Object) { $this->$Object = loadClass($Object); } } } Code: [Select] <?php class Model extends Base { function Model() { parent::Base(); echo $this->Input->UserAgent(); } } Code: [Select] <?php class Home extends Controller { function Home() { parent::Controller(); } function index() { $this->Loader->Library('Session'); $this->Loader->Library('Model'); $Data = array( 'Controller' => $this->Router->FetchClass(), 'Title' => ucfirst($this->Router->FetchClass()) ); $this->Loader->View('meta',$Data); $this->Loader->View('header',$Data); $this->Loader->View('home'); $this->Loader->View('footer'); } } Any input would be appreciated! So, I have what I think is an odd question. I have a function that contains a for loop. Within that for loop, it checks for a new condition and if it is true, it calls the very function it's already in. So, within the for loop inside of function "a", it can call function "a" with new arguments which will then start a new for loop to be "nested" to the previous for loop, in a way. My problem is trying to keep the values of the variables so that once the new for loop (or loops) finish, the previous for loop won't be stopped up by the new variable values that have since changed. Make sense? So, two questions: 1. How do I lock in values that make them unique to that very call of that function and keep them unique through further iterated versions? 2. I imagine, in theory, that for loops stay in memory in state as a new "instance" of that same for loop runs through, right? Basically, is what I'm doing possible in that a for loop calls itself, in essence, to create a new "instance" of that for loop, then when it finishes, have the previous loop continue iterating? For question #1, I've already thought about using variable variables, but that doesn't work because every time the function is called, the variable variable will change to new values based on the new arguments and instantiating the function again. I'm kind of looking for a way to make unique "instances" of a method that don't mess with future calls to that method and where future calls don't mess with currently iterating loops in that method. Phew, I think I confused myself. Thanks for any help. Hello, I need to find the target html address within some raw html. I know it lies between Needle 1 and Needle 2 below. Needle 1: </span></a> <a href=" Needle 2: " rel="nofollow"><span class=pn><span class=np>Next »</span></span></a></div> Nornally I would just use the explode() function but my headache is that there are many instances of Needle 1 in the raw html code and I want my output array always have the same number of elements. However I do know that my target html address is directly after the last instance of Needle 1. How should I go about splitting the html code into an array that always has 3 elements? I'd like the first element to include code up to and including the last instance of Needle 2, the 2nd element to have the target html address, and the 3rd element to have Needle 2 and any following code. Thanks for any pointers (my main struggle is identifying the last instance of needle 1), Thanks, Stu Hope someone can help, I am trying to add up all the values of a variable in a PHP while loop and have tried several approaches but none seem to work. Hopefully someone can point out what the correct method is. I've set up some code to pull the pay rate from a MySQL table, and then calculate that person's earnings based on the amount of time they spend on a particular job. That works fine:
However there may be a number of jobs for different people with different rates, so I want to add all of these up and output the total. So for example if I had values of 125.00, 35.50 and 22.75 I want to show 183.25 as the total. So I tried a few things I found on forums on the subject:
That didn't work so I tried another method that someone suggested:
The 2nd method outputted just the last individual value, the 1st method didn't work at all. Does anyone have a working method that can be used to do this? Thanks Hey, I'm trying to save a MySQL-Link source as an instance variable in my query class. The problem is that MySQL sees it as an invalid MySQL-Link (supplied argument is not a valid MySQL-Link resource). What I'm I doing wrong? //Walle Code: [Select] private $connection; //Construct public function __construct(&$connection) { $this->connection = $connection; } //Where the error occurs public function exe_query($sql) { $result = mysql_query($sql, $this->connection); if(!$result) { throw new Exception(mysql_error()); } return $result; } Hi, I have an output of print_r he
Google_Service_Calendar_Acl_Resource Object ( [stackParameters:Google_Service_Resource:private] => Array ( [alt] => Array ( [type] => string [location] => query ) [fields] => Array ( [type] => string [location] => query ) [trace] => ArrayI am wondering what is the right syntax to create the instance and set the variables? Thanks, Ted I know you can use str_replace to replace a value with another value, or an array of values with an array of other values. What I'd like to do is replace each instance of a single value with an array of values which get iterated through for each instance found. Think prepared statements that you don't have to call setString or setInt on. Here's a made up example. Code: [Select] $db->query = 'SELECT * FROM users WHERE user_name = ? AND user_role = ?; $db->params = array('hopelessX','admin'); $db->executeQuery(); //this contains a call to a private function that does the replace I have everything else working except this. It works if I specify an array of values to replace and do something like below, but I was hoping to not have to support that method of replace if I didn't need to. Code: [Select] $db->query = 'SELECT * FROM users WHERE user_name = :name AND user_role = :role; $db->replace = array(':name',':role'); $db->params = array('hopelessX','admin'); $db->executeQuery(); //this contains a call to a private function that does the replace I can do it that way if I need to or I could make some overly complicated thing that finds each instance of the question mark, replaces it with a unique value and then adds that unique value to a replace array similarly to the method in code block two but that defeats to the purpose of making this simple database adapter in the first place (although it was mostly just for fun anyway). Anyway, if anyone has any advice and knows of a simple means to achieve this goal that would be much appreciated. Thanks in advance Hi, I'm just wondering if there's any way to use the Limit to limit a search to the first instance of multiple items in one column? Eg, in a table called news I might have: subject content general general news1 general generalnews2 faq faq1 faq faq2 general generalnew3 When I do Code: [Select] SELECT * FROM news ORDER BY content DESC LIMIT 0,1(same if I substitute the word subject for content in the line above) ...I get just the first item. Ie: subject content general generalnews1 How would I go about getting the first instance of each subject and its contents to appear? Ie: subject content general generalnews1 faq faq1 Thanks, Dave I have a table that contains the schools in my system: schools id name location ... Then, I have three tables that use the id of this table: schoolAdmins schoolID schoolContests schoolID students schoolID When I go to delete a school from my system, I want to check to see if that school is connected to any of these three other tables first. This is what I tried (but obviously failed because I'm here) where I'm passing the query the $studentID in question: SELECT * FROM schoolAdmins, schoolContests, students WHERE (schoolAdmins.schoolID = $schoolID) OR (schoolContests.schoolID = $schoolID) OR (students.schoolID = $schoolID) I'm really new to the concept of querying multiple tables in a single statement, so I'm just kind of guessing at this point. Thanks in advance. I have a scenario in PHP, i need a smart way: 1. I run one process on background forever, scheduler.php - done 2. User on the web submit their task in DB to be processed by the above process(scheduler.php) - done 3. scheduler.php read the db after every 1 sec, looking for user's task. Problem: Ideally, if it founds like 10 or more tasks it should process them concurently(in parallel)..i.e it should not wait one task to be fully executed so as to run the next one as one task might take a very long time to be fullu executed. I would do like exec("nohup php <path>/file_name.php >> /dev/null 2>&1 &"), but if i have alot of tasks this will create zombie processes. Any smart way to do this will be highly appreciated! Hi all, I have a security problem with my website who is a social network (like facebook). Let's me Explain : You can execute this page on my website. www.SocialNetWork.com/ChangeStatus.php?param=Hello So your status become "Hello". On your profile, you can create a link to a picture on the web, for example : <img src='http://www.hacking.com/pic.jpg'> The problem is that a "hacker" create several russian girl profile and made links to pic.jpg on his server, and this .jpg file rewrite URL to : www.SocialNetWork.com/ChangeStatus.php?param=Suck. So when you visite his profil, the php code is launched, and the status OF THE VISITOR is changed ! I have no idea of how to stop this ? If i check the variable : $_SERVER['HTTP_REFERER'] The value is empty or www.SocialNetWork.com, but never www.hacking.com ... How can i stop the fact that a foreign picture could launch a php page on my website ? thanks for help ! ps: sorry for my english I would like to better understand relative and absolute paths when rewriting URLs. My virtual host configuration is shown below. I wish the server to see something like: https://example.com?page=page1&controller=controller1&data1=123&data2=321Given the rewrites as shown in my virtual host, what would be the proper URL in the browser? One of these (note the ? and &), or something different? https://example.com/page1/controller1?data1=123&data2=321 https://example.com/page1/controller1&data1=123&data2=321Next, if I enter one of the URLs, how do relative paths to images, etc work? Would the browser think it is in the root directory, or in /page1/controller1? I had problems with relative paths, and changed to absolute paths, and it fixed the problem, but I wish to better understand what is happening. On a side note, I would appreciate any critique of my virtual host configuration. My goal is for all requests to example.com to redirect to https://example.com, for only https://example.com (no subdomain) to redirect to https://www.example.com, and do the rewriting of page and controller. Thank you # Note that if a virtual ServerName is not found (i.e. IP 192.168.1.200), Apache defaults to first virtual host. # Note that if ServerName is set to one of the virtual host ServerName's in the Second Section, it doesn't work (why?) # Handle just example.com to http <VirtualHost *:80> ServerName example.com ServerAlias *.example.com Redirect / https://www.example.com/ </VirtualHost> # Handle just example.com without subdomains <VirtualHost *:443> ServerName example.com # ServerAlias example.com SSLEngine on SSLCipherSuite SSLv3:TLSv1:+HIGH:!SSLv2:!MD5:!MEDIUM:!LOW:!EXP:!ADH:!eNULL:!aNULL SSLCertificateKeyFile /etc/pki/tls/private/example_key.pem SSLCertificateFile /etc/pki/tls/certs/example_startssl.crt SSLCertificateChainFile /etc/pki/tls/certs/sub.class1.server.ca.pem Redirect / https://www.example.com/ </VirtualHost> <VirtualHost *:443> ServerName example.com ServerAlias *.example.com DocumentRoot /var/www/example/html SSLEngine on SSLCipherSuite SSLv3:TLSv1:+HIGH:!SSLv2:!MD5:!MEDIUM:!LOW:!EXP:!ADH:!eNULL:!aNULL SSLCertificateKeyFile /etc/pki/tls/private/example_key.pem SSLCertificateFile /etc/pki/tls/certs/example_startssl.crt SSLCertificateChainFile /etc/pki/tls/certs/sub.class1.server.ca.pem <Directory "/var/www/example/html"> allow from all Options +Indexes <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / # Are these lines necessary, or should I create a virtual host for http on port 80 instead? RewriteCond %{HTTPS} !=on RewriteRule .* https://%{SERVER_NAME}%{REQUEST_URI} [NE,R,L] ## If the request is for a valid directory, file, or link, don't do anything RewriteCond %{REQUEST_FILENAME} -d [OR] RewriteCond %{REQUEST_FILENAME} -f [OR] RewriteCond %{REQUEST_FILENAME} -l RewriteRule ^ - [L] #remove the trailing slash RewriteRule (.+)/$ $1 # If you add this first rule to support views, be sure to remove the QSA flag from the second rule (maybe not required since the first rule has the L flag) #replace mypage/mycontroller with index.php?page=mypage&controller=mycontroller RewriteRule ^([^/]+)/([^/]+)/?$ index.php?page=$1&controller=$2 [L,QSA] #replace mypage with index.php?page=mypage RewriteRule ^([^/]+)/?$ index.php?page=$1 [L,QSA] </IfModule> </Directory> </VirtualHost> It has been brought to my attention that $_SERVER['PHP_SELF']; can be easily hacked. In this code... Code: [Select] <form id="login" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"> Do I even need anything in the Action attribute if I am redirecting the form to itself?! Please advise... Debbie This topic has been moved to mod_rewrite. http://www.phpfreaks.com/forums/index.php?topic=359560.0 I have mysqli object in Database class base: [color=]database class:[/color] class Database { private $dbLink = null; public function __construct() { if (is_null($this->dbLink)) { // load db information to connect $init_array = parse_ini_file("../init.ini.inc", true); $this->dbLink = new mysqli($init_array['database']['host'], $init_array['database']['usr'], $init_array['database']['pwd'], $init_array['database']['db']); if (mysqli_connect_errno()) { $this->dbLink = null; } } } public function __destruct() { $this->dbLink->close(); } } Class derived is Articles where I use object dBLink in base (or parent) class and I can't access to mysqli methods (dbLink member of base class): Articles class: require_once ('./includes/db.inc'); class Articles extends Database{ private $id, .... .... $visible = null; public function __construct() { // Set date as 2009-07-08 07:35:00 $this->lastUpdDate = date('Y-m-d H:i:s'); $this->creationDate = date('Y-m-d H:i:s'); } // Setter .... .... // Getter .... .... public function getArticlesByPosition($numArticles) { if ($result = $this->dbLink->query('SELECT * FROM articles ORDER BY position LIMIT '.$numArticles)) { $i = 0; while ($ret = $result->fetch_array(MYSQLI_ASSOC)) { $arts[$i] = $ret; } $result->close(); return $arts; } } } In my front page php I use article class: include_once('./includes/articles.inc'); $articlesObj = new articles(); $articles = $articlesObj->getArticlesByPosition(1); var_dump($articles); [color=]Error that go out is follow[/color] Notice: Undefined property: Articles::$dbLink in articles.inc on line 89 Fatal error: Call to a member function query() on a non-object in articles.inc on line 89 If I remove constructor on derived class Articles result don't change Please help me |