PHP - Difficulty Layering Objects
Hello everyone. Before I start, I'm relivily new to PHP but have been doing it for a few weeks or so, my latest problem that i've been trying to crack for a few days now is using the "imagecopy" command in php, I'm working on an avatar script that lets users design there own avatar, selecting clothes, hair, eyes, etc. I've only just started and i've ran into a rather large problem so don't seem to be able to move any further,
This is the code i have Quote <?php ob_start (); /* background */ $bg = imagecreatefrompng('bg.png'); /* foreground */ $fg = imagecreatefrompng('fg.png'); /* frontground */ $fgg = imagecreatefrompng('fgg.png'); $x = imagesx($bg); $y = imagesy($bg); imagecopy($bg, $fg, $fgg, $x, $y); header('Content-Type: image/png'); imagepng($bg); imagedestroy($bg); imagedestroy($fg); imagedestroy($fgg); ?> However for some reason, probably a simple fault, it's just giving me a broken image link? I'm not sure why it's doing this if you want to see exactly what it's doing please look at http://chat.blastgames.org/index.php Like i say i'm clueless so any help would be much appreciated, Also if anyone knows of any downloadable php avatar scripts that lets you customize things like hair, clothes etc. please tell me, I've been searching for one for a while, Thanks for reading , Any help will be much appreciated. Similar TutorialsHello all!
I have this array of objects:
Array ( [0] => stdClass Object ( [first_name] => test [last_name] => test [title] => test [id] => 34 [type] => 4 [manager] => 4 [email] => p@yahoo.com [date] => 2014-09-21 07:23:12 [status] => 2 [approval_date] => 2014-09-21 07:31:10 [assessment_id] => 1 [supervisor_approval] => 1 [manager_approval_date] => 2014-09-21 07:31:27 [mainmanger] => 3 ) [1] => stdClass Object ( [first_name] => test [last_name] => test [title] => test [id] => 34 [type] => 4 [manager] => 4 [email] => p@yahoo.com [date] => 2014-09-20 07:39:55 [status] => 2 [approval_date] => 2014-09-20 07:40:41 [assessment_id] => 3 [supervisor_approval] => 1 [manager_approval_date] => 2014-09-20 07:41:07 [mainmanger] => 3 ) [2] => stdClass Object ( [first_name] => jimmy john john [last_name] => john [title] => Lorad and Master [id] => 32 [type] => 4 [manager] => 3 [email] => j@j.com [date] => 2014-09-21 07:38:50 [status] => 2 [approval_date] => 2014-09-19 07:39:25 [assessment_id] => 2 [supervisor_approval] => 1 [manager_approval_date] => 2014-09-19 07:39:25 [mainmanger] => 0 ) )Where "id" = the user ID. If there are two or more entries for a user, I want to remove all but the most recent by the "approval_date",... So for the above example it would return: Array ( [0] => stdClass Object ( [first_name] => test [last_name] => test [title] => test [id] => 34 [type] => 4 [manager] => 4 [email] => piznac@yahoo.com [date] => 2014-09-21 07:23:12 [status] => 2 [approval_date] => 2014-09-21 07:31:10 [assessment_id] => 1 [supervisor_approval] => 1 [manager_approval_date] => 2014-09-21 07:31:27 [mainmanger] => 3 ) [1] => stdClass Object ( [first_name] => jimmy john john [last_name] => john [title] => Lorad and Master [id] => 32 [type] => 4 [manager] => 3 [email] => j@j.com [date] => 2014-09-21 07:38:50 [status] => 2 [approval_date] => 2014-09-19 07:39:25 [assessment_id] => 2 [supervisor_approval] => 1 [manager_approval_date] => 2014-09-19 07:39:25 [mainmanger] => 0 ) )I'm having a hard time wrapping my head around this concept, so I don't have any example code. And I don't really need or expect someone to code this for me,. just a push in the right direction would be awesome. I have the following three tables (and also delta_point and hist_point which are purposely left out and just mentioned for context). Before going down the Doctrine ORM long curvy road, aggrType was just used to restrict possible values so that I didn't need to use MySQL's ENUM, but now I am thinking there may be value to making it an entity and include some methods (and a second reason because I still can't figure out how to make Doctrine create a FK constraint yet not populate the parent entity with a AggrType object). point -id (int PK) -data -dType /* descriminator. Options are AggregatePoint, DeltaPoint, and HistoricPoint */ aggr_point -id (int PK, FK to point) -aggrType (char FK to aggrType) -data aggrType -type (char PK) /* there are about five types */ I have a service to create a new point based on the provided desired type and user data. I don't like the switch statement to determine which type of point to create, but don't know a better way. Also my entity is responsible to provide the appropriate validation rules for the given point type which might not be considered proper but it seems to work for me. Any constructive criticism is welcomed. <?php namespace NotionCommotion\PointMapper\Api\Point; use NotionCommotion\PointMapper\Domain\Entity\Point; class PointService { public function create(string $type, array $params):integer { $class=[ 'aggr'=>'AggregatePoint', 'delta'=>'DeltaPoint', 'hist'=>'HistoricPoint', ][$type]; //$class='Point\\'.$class; //This doesn't seem to be possible and I needed to use the fully qualifed name without the short cut used namespace. $class='\\Greenbean\Datalogger\Domain\Entity\Point\\'.$class; $point=new $class(); $validator=$this->getValidator($point); $params=$validator->sanitize($params); $validator->validate($params); $point->setAccount($this->account); $point->populate($params, $this->em); //Will be addressed later $this->em->persist($point); $this->em->flush(); $point->setIdPublic($this->em->getRepository(Point\Point::class)->getPublicId($point->getId())); return $point->getIdPublic(); } } Now, this is the part I am struggling with the most. I only have one service to create any type of point, so I do wish to put a bunch of if/thens in it and instead move logic to the individual point type being created. The AggrPoint in question requires a sub-point and I don't think it is appropriate to inject the entity manager into a point entity and as an alternative solution find an existing point which is associated with the account which resides in the new AggrPoint. Maybe not appropriate, but it works. This type of point also has a sub-object AggrType as discussed at the very beginning of this post, so I first attempt to create a new one from scratch, but that doesn't work and I need to set $aggrType with an existing one. As an alternative, I passed the entity the entity manager, but as stated I think this is a bad idea. Any recommendations where to go from here? Thank you namespace NotionCommotion\PointMapper\Domain\Entity\Point; class AggregatePoint extends Point { public function populate(array $params, \Doctrine\ORM\EntityManager $em):\NotionCommotion\PointMapper\Domain\Entity\Entity{ $criteria = \Doctrine\Common\Collections\Criteria::create() ->where(\Doctrine\Common\Collections\Criteria::expr()->eq("id_public", $params['pointId'])); if(!$subpoint = $this->getAccount()->getPoints()->matching($criteria)->current()){ throw new \Exception("Invalid subpoint ID $params[pointId]"); } $this->setSubpoint($subpoint); //This won't work since I must use an existing AggregateType and not create a new one $aggrType=new AggregateType(); $aggrType->setType($params['aggrType']); //This just seems wrong and I shouldn't be passing the entity manager to an entity $aggrType=$em->getRepository(AggregateType::class)->findOneBy(['type'=>$params['aggrType']]); $this->setAggregateType($aggrType); unset($params['pointId'], $params['aggrType']); // parent::populate($params) not shown, but it basically calles appropriate setters based on the property name return parent::populate($params); } public function getValidatorRules():array { return $this->filesToArr(['/point/base.json', '/point/aggr.json']); } }
Hi All. I am new to PHP, but am learning. I have set myself a mini project to learn some new php and to have some fun! I was hoping that someone would be kind enough to tell me how difficult this would be to achieve, and how they would best suggest to approach it. I want to create a 'availability checker'. I want to create a field where I can input a date. If the date exists in my mysql database then it returns NO, if the date isn't in the database it returns YES. For a admin area I want to have a place to add dates, and maybe some details about these dates. I don't think its overly complicated, but it should still be quite a challenge for me. Any guidance would be greatly appreciated. Thanks Hi guys.
I have tried implementing PDO in my php. Basically, I have created a form, which will take a letter, and then pass it to the php file.
My hope was, whatever was entered by the user, whether that was in the guise of being manually entered by them or chosen by a dropbox etc, this would then be able to be used within the LIKE comparison. When I run my file however, I get the following message: Error: SQLSTATE[HY093]: Invalid parameter number: no parameters were bound. I am a little confused by this. I have used $_POST with the HTML form element, and have specified it in the SQL syntax. Can anyone please advise me as to where I am going wrong? Hello! I'm having trouble with a class that extends another, and I don't think I understand the 'extends' concept properly. I've had my nose in various manuals, but I haven't had any luck figuring it out. Here's a simplified version of my code: Code: [Select] class Position { private $latitude = 0; private $longitude = 0; public function getLatitude(){ return $this->latitude; } public function getLongitude(){ return $this->longitude; } } class Coordinates extends Position { function __construct($nlat, $nlong){ $this->latitude = $nlat; $this->longitude = $nlong; } } $lat = -123; $long = 44; $coordFirst = new Coordinates($lat,$long); print($coordFirst->getLatitude()); I expect -123 to be printed, but I always get 0 instead. Could someone let me in on what I'm missing here? Thanks a bunch! Hi, I have an interface where the user picks an image to upload, it then uploads the original (big) image. That same image then appears but at a reduced size of 150px max height or width, the size is defined in the img tag using height="XX" width ="XX", so it is the same image file, just with its dimensions set in the html. The user then drags a div over the image to crop it. The problem I am having is getting the reference image crop dimensions to translate to the actual full size image. Have attached an image of what the result is. What formula do I need to get it to translate to the bigger image properly? Here is my code: if($_GET['mode'] == 'imageupload') { $imgNumber = $_GET['img'] ; $fileName = strtolower($_FILES["setFile$imgNumber"]['name']) ; $ext = explode('.', $fileName) ; if($ext[1] != 'jpg' && $ext[1] != 'JPG' && $ext[1] != 'jpeg') { echo "<span class='iFOutput'>Can only accept JPG images.<br /><br /> The image you tried to upload was '" . $ext[1] . "'.</span>" ; exit() ; } $tmpName = $_FILES["setFile$imgNumber"]['tmp_name'] ; move_uploaded_file($tmpName, '../uploads/' . $fileName) ; $sizeInfo = getimagesize('../uploads/' . $fileName) ; $resizedArray = imageResize($sizeInfo[0], $sizeInfo[1], 204) ; $finalImageSrc = '../uploads/' . $fileName ; echo '<img id="image' . $imgNumber . '" src="' . $finalImageSrc . '" width="' . $resizedArray[0] . '" height="' . $resizedArray[1] . '" />' ; // SCALED IMAGE FOR CROPPING INTERFACE } elseif($_GET['mode'] == 'imagecrop') { $imgSrc = $_POST['imagePath'.$_GET['img']] ; $thisX1 = $_POST['image' . $_GET['img'] . 'X1'] ; $thisY1 = $_POST['image' . $_GET['img'] . 'Y1'] ; $thisX2 = $_POST['image' . $_GET['img'] . 'X2'] ; $thisY2 = $_POST['image' . $_GET['img'] . 'Y2'] ; $original = imagecreatefromjpeg($imgSrc) ; list($width, $height) = getimagesize($imgSrc) ; if ($width > $height) { $ratio = (150 / $width); } else { $ratio = (150 / $height); } echo $ratio ; $thumbCanvas = imagecreatetruecolor(150, 150) ; $thisX1 = round($thisX1/$ratio) ; $thisY1 = round($thisY1/$ratio) ; imagecopyresampled($thumbCanvas, $original, 0, 0, $thisX1, $thisY1, 150, 150, $width, $height) ; imagejpeg($thumbCanvas, '../uploads/thumbnail.jpg') ; echo '<img id="image' . $_GET['img'] . '" src="' . '../uploads/thumbnail.jpg' . '" />' ; } How hard would it be to build a basic Online Forum using PHP? (Yes, I know there are open-source versions out there a plenty, but what fun is that?!) I have a book by Larry Ullman that describes how to do it, but I don't have the book with me and have never programmed such a thing - obviously - so I'm not sure how hard it would be and what you would get for the effort?! Thanks, Debbie Hi, I have a form that I want to allow users to be able to add specific links, some are set types (domains) and just require the iser to enter the link, however, one is for whatever they wish and they must enter a name to describe it. Now im going to enter it into a database with the following columns: USER_ID || LINK_URL || LINK_TYPE || LINK_NAME Link name is optional (only needed if the link type is their own custom one), the link types are ID's related to a table of link types (facebook, twitter etc). Now I'm assuming that to differentiate the form elements for insertion into the database I would need to have a hidden form element with the type ID inside? However I don't really know how to go on from here. A small version of the form would be <input type="text" name="facebook_link" /> <input type="hidden" name="facebook_id value="1" /> <input type="text" name="twitter_link" /> <input type="hidden" name="twitter_id value="2" /> <input type="text" name="own_site" /> <input type="text" name="own_site_description" /> <input type="hidden name="own_site_id" value="3" /> However, I'm assuming this is wrong because I'll need to enter everything into an array won't I? I just can't get my head round it to out put thi results into a foreach statement. Can anybody help me please? I'm having a problem with (what I'm almost certain is) variable scope, maybe you can help... So I've got a parent class that, among other things, gets the name of the filepath, explodes this filepath, checks for files with names that mirror that filepath (without the slashes of course), and includes them if they exist: class ParentClass { public $RootFolder; public $PageSections; function __construct() { global $root_folder; $this->RootFolder = $root_folder; //get all directory names... $cleanse = $this->RootFolder; $pagepath = str_replace($cleanse, '', dirname($_SERVER['PHP_SELF'])); $this->PageSections = explode('/', $pagepath); } function RequireIfExists ($sections, $root_folder, $file_name, $file_type) { foreach ($sections as $i){ if (isset($o)) { $i = $o."/".$i; } $file = $root_folder.$i."/".$file_name.$file_type; if (file_exists($_SERVER['DOCUMENT_ROOT'].$file)) { require ($_SERVER['DOCUMENT_ROOT'].$file); echo "<!--".$file." included -->"; //temporary measure to ensure that the file is at least being called. } $o = $i; } } // so, excuting the function // $this->RequireIfExists($this->PageSections, $this->RootFolder, "sectionvars", ".php"); // on some/sub/folder/index.php // will look for somesectionvars.php, somesubsecitonvars.php & somesubfoldersectionvars.php // and include whichever ones exist. } Then there is a child class that utilizes this function, and successfully requires the file. I know the file is coming through because the echo statement on the page shows up in the code, but I cannot get the variables to pass through? <?php class HtmlHead extends PageBlock{ public $PageKeywords; public $PageDescription; public $PageStyles; public $PageScripts; //------------------------ public $SectionKeywords; public $SectionDescription; //------------------------ public $SiteKeywords; public $SiteDescription; public $SiteStyles; public $SiteScripts; //------------------------ public $CatchAll; function __construct() { parent::__construct(); //$this->RequireIfExists($this->PageSections, $this->RootFolder, "sectionvars", ".php"); //I have tried calling the function here with no luck global $site_description, $site_keywords, $section_description, $section_keywords, $xyz; //also made sure to global the variables from the required page $this->SiteDescription = $site_description; $this->SiteKeywords = $site_keywords; $this->SectionDescription = $section_description; $this->SectionKeywords = $section_keywords; $this->PageDescription = $page_description; $this->PageKeywords = $page_keywords; } function Constructor() { $this->RequireIfExists($this->PageSections, $this->RootFolder, "sectionvars", ".php"); //Tried calling the function here as well, no luck global $xyz; //global'd the var i want echo "\n<meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />"; echo "\n<!--Sec Keywords are".$xyz."-->"; //Tried to echo the var... //------------------------Rest of code... } } And here is the page that is being required... <?php echo "<!-- 1234 1234 1234 1234 -->"; //test measure to see if/where file is including $section_keywords = "red, secondary"; $section_description = "this is the red section description"; $xyz = "1234"; //test Var to see if there was a naming conflict with the above two.. ?> What am I overlooking this time? Hello,
I recently posted here about an issue I was having with my database orientated products page.
I have now run into another problem where say if, /db.php was typed or /db.php?p=IDoNotExist was typed, it returns blank.
I have in my code the desired content to be displayed, but it just doesn't seem to want to make a show.
I was also wondering if it is possible to show different content for whatever the URL is, so for no parameter, the content about the products, and a non existent one, maybe "Product not found"?
Here is my code:
<?php $db=mysql_connect ("localhost", "webwibco_charlie", "Hello123") or die ('I cannot connect to the database because: ' . mysql_error()); $mydb=mysql_select_db("webwibco_products"); include("header.php"); $status = htmlspecialchars( @$_GET ['p'] ); if ($status == "floorpuzzles") { echo "<h1>Our Floor Puzzles</h1>"; $sql="SELECT ID, Name, Tags, Description, Category FROM products WHERE Category LIKE '%" . FloorPuzzles . "%'"; $result=mysql_query($sql); while($row=mysql_fetch_array($result)){ $Name =$row['Name']; $ID =$row['ID']; $Description =$row['Description']; echo "<div class=\"box\">"; echo "<h1>$Name</h1>"; echo "<div class=\"floorbox\"><a href=\"?p=$ID\"><img src=\"images/products/catalogue/big/floorpuzzles/$ID.jpg\" class=\"small\"></a></div>"; echo "<h2>$Description</h2>"; echo "</div>"; } ?> <? }else{ if ($status == $_GET["p"]) { $sql="SELECT ID, Name, Tags, Description, Pieces, Size, Barcode, Category FROM products WHERE ID = '" . $_GET['p'] . "'"; $result=mysql_query($sql); while($row=mysql_fetch_array($result)){ $Name =$row['Name']; $ID =$row['ID']; $Description =$row['Description']; $Pieces =$row['Pieces']; $Size =$row['Size']; $Barcode =$row['Barcode']; echo "<div class=\"1\">"; echo "<h1>$Name</h1>"; echo "<div class=\"bigbox\">"; echo "<div class=\"floorbox\"><img src=\"images/products/catalogue/big/floorpuzzles/$ID.jpg\" class=\"big\"></div>"; echo "</div>"; echo "</div>"; echo "<div class=\"2\">"; echo "<p>Puzzle Pieces: $Pieces</p> <p>Puzzle Size: $Size</p> <p>Barcode: $Barcode</p>"; echo "</div>"; } }else{ ?> <? echo"<h1>Our Products</h1> <p>Our jigsaw puzzles are hand cut by skilled craftsmen and therefore each one is unique with self-correcting pieces. There is a strict quality control process at all stages by our highly experienced staff. The puzzles are durable and provide fun and excitement, enhancing learning and a child’s development.<p> <p>All of our jigsaws are made using materials from sustainable resources grown in managed forests. Where possible we support companies in the UK and source our components locally, most of our suppliers are in the East Midlands, many in Derbyshire and Nottinghamshire. We keep packaging to a minimum and take our environmental and ethical responsibilities very seriously.</p> <p>Reducing waste and recycling was a way of life for us before it became fashionable. We are constantly searching for new ideas and consult teachers when developing our jigsaws, which are often used within the national curriculum.</p> <p>As well as making our own range, we manufacture for leading suppliers to the education market. Check for \"Made in Britain\" and it is probably made by us.</p> <p>We have a wide variety of products available for viewing, from classic floor puzzles to innovative inset trays. You can take a look at all our products on this page, simply use the navigation buttons to your left.</p>"; }} include("footer.php"); ?>The final echo is what I wish to be displayed on the URL without or with an invalid parameter. Here is my site URL: http://www.webwib.co...saws/search.php (note that only the "Floor Puzzles" category has content within it). Thank you in advance for assistance. Hi I am new to PHP and I need to create an array and add both books to the array and than loop through the array this is where I am having trouble if the price of a book is less than $20.00 output the book’s name and price if the book’s title comes after the letter R in the alphabet output the book’s title. I am getting these error:
Notice: Trying to get property 'price' of non-object in C:\xampp\htdocs\PHP objects\books.php on line 45 My code is:
<?php
// Methods
$first_book = new Book();
foreach ($book as $bookItem) { Any help will be very much appreciated Thank you I took an object, and saved it into a database serialized. Code: [Select] $object_here = serialize($theobject); Then later on, I go and I get that data from a database, and try to unserialize it.. Code: [Select] $objecthere = unserialize($row->theobject) And it throws the following error...any advice? Quote Warning: unserialize() [function.unserialize]: Node no longer exists in /path/to/file on line 20 I know it is often frivolous, but sometimes I can't help trying to optimize things, and use the following two methods to create either an object injected with a string or one of a set of objects. For both cases, the class has no setters so there is no chance that the object will later be changed. I first stated doing this in continuously running server applications which I believe makes sense, however, it has leaked over to standard HTTP requests. Please commit good or bad on this approach. Thanks
public static function create(string $unit):self { static $stack=[]; if(!isset($stack[$unit])) { $stack[$unit] = new self($unit); } return $stack[$unit]; } public static function create(string $class):FunctionInterface { static $stack=[]; if(!isset($stack[$class])) { $stack[$class] = new $class; } return $stack[$class]; }
I found it helpful to configure all my objects in one or several bootstrap scripts. Before doing so, I would often find myself forgetting that I already had written some class which is located deep in some script and recreating it for some other need (granted, composer definitely helped in this regard, but using it wasn't always applicable). <?php $c=new Pimple\Container(getMySettings()); $c['pdo'] = function ($c) { $db = $c['settings']['mysql']; return new \PDO(bla); }; $c['foo'] = function ($c) { return new Foo( $c->get('pdo') ); }; $c['bar'] = function ($c) { return new Bar( $c->get('foo') ); }; It is all good until I find myself needing to create some new instance of some class instead of just passing some common instance to whoever needs it. class Foo { private $pdo; public function __construct(\PDO $pdo) { $this->pdo=$pdo; } public function getSomething():SomeClass { return new SomeClass($this->getAllDataFromDB($GET['id'])); } } class SomeClass { private $arr; public function __construct(array $records) { foreach($records as $record) { $arr[]=new SomeOtherClass($record); } } } I've read that one shouldn't create new objects in a given class's constructor, and while I could instead do so in some class's method and pass the object to the given class's constructor, to me it seems to really be the same thing. The three issues I have with this scenario a Needing to remember that these classes exist as they are hidden deep in some classes. Makes it more difficult to replace one of the classes with some other class in the future. Some duplication of code.Are there other compelling reasons not to do so? Is it worth the effort to do differently? If so, how would you recommend doing so? My thoughts would either to use Pimple's factory() method are create my only factory which also relies on anonymous functions. Maybe something else? $c['someClass'] = $c->factory(function (array $record, Container $c) { return new SomeClass($record); }); Thanks Hi all,
I am working with the following 2 page script: https://github.com/k...hi/php-riot-api. All works well and the data is pulled via the API as intended. However, depending on the data I'm trying to display on screen, the object contains multiple values.
For example:
$r = $test->getSummoner($summoner_id,'name'); print_r($r);outputs their ID and name: {"585897":"TheirName"} Just as the following: $r = $test->getSummonerByName($summoner_name); print_r($r);outputs username, ID, Name, profile icon ID, level, and timestamp: {"theirname":{"id":585897,"name":"TheirName","profileIconId":642,"summonerLevel":30,"revisionDate":1405652924000}} Depending on which function I am calling (on example.php), I would like to be able to split the values so I can echo them throughout a page: Name: <value> ID: <value> Level: <value> etc... Any guidance would be appreciated. In a relational database, you "link" tables together. For example, Customer (parent) ---> Product (child) How do you do that with Objects? I have a "User" class and an "AddressBook" class. A User can have zero or more Addresses (in their AddressBook). If I create a User object and an AddressBook object, I need a way to link them up similar to how they are linked up in the database. Make sense?! TomTees Hi guys, I am currently building a customer appointment booking system with PHP. Customers who are added are store on a customer database and displayed or listed as links dynamically in a 'customer.php' page. So you can click on a customer to view their profile i.e. name, address, time added, an so on. Also there is a button to 'create appointment' for the customer. Click the button, a form appear, select a day and time the click submit. It all works fine. The problem is once the appointment is booked I dont how to remove the customer from the list on the customer.php page. So am looking for something like what they have on e-commerce sites e.g a customer buys an item and that item is no longer available for another customer. Please guys am calling for your expertise, any ideas, inputs or suggestions you may have are more than welcome. Thanks I can post some code once I am back at my laptop but for now thinking about this is keeping me awake in bed and all I have handy is my phone. Anyway, I am new to OOPHP. I have a class that I created. I have two objects/instances of it, each using some of the same and some different methods within the class. When I run the page either of the instances works great alone but I get the white screen of death when I try to use both instances at the same time. Any ideas or places I should start? Ever since I started using OOP this past week, I have not been able to go back to the old "procedural" methods. HOwever, I seem to be stuck on creating a mysql connection that I can reuse in all of my classes. After I set up a connection to mysql using the mysqli object, I am unable to use the mysqli in other objects. Code: [Select] $mysqli = new mysqli(.....); class new_class { function quickQuery () { $mysqli->query('some query') } } Obviously, this doesn't work, because $mysqli is not defined within that functions scope. One way, is to use global keyword. Code: [Select] global $mysqli However, globals "are the root of all evil" and simply go against the idea of encapsulation in OOP. What's a way around this? HOWEVER: 1) I still want to use the mysqli object 2) I don't want to reference the $link of the db each time I instantiate a new class .... Maybe I'm asking too much? And I've google for the past hour or so. Singleton seems interesting but it requires the creation of a new db connection class. I want to use the mysqli object. Hello, I want to make a list with 2 columns on one of my pages with link to categories on my page. But they appear in only one column (on below the other) and i want them to be like: Pictures Videos Pictures2 Videos2 These are my codes <li> <a href="user_album_add.php">Pictures</a> <li> <a href="user_album2_add.php">Pictures2</a> <li> <a href="user_video_add.php">Video</a> <li> <a href="user_video2_add.php">Video2</a> What should i do? Thank you! |