Jump to content

Search the Community

Showing results for tags 'oop'.

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Forums

  • Welcome to PHP Freaks
    • Announcements
    • Introductions
  • PHP Coding
    • PHP Coding Help
    • Regex Help
    • Third Party Scripts
    • FAQ/Code Snippet Repository
  • SQL / Database
    • MySQL Help
    • PostgreSQL
    • Microsoft SQL - MSSQL
    • Other RDBMS and SQL dialects
  • Client Side
    • HTML Help
    • CSS Help
    • Javascript Help
    • Other
  • Applications and Frameworks
    • Applications
    • Frameworks
    • Other Libraries
  • Web Server Administration
    • PHP Installation and Configuration
    • Linux
    • Apache HTTP Server
    • Microsoft IIS
    • Other Web Server Software
  • Other
    • Application Design
    • Other Programming Languages
    • Editor Help (PhpStorm, VS Code, etc)
    • Website Critique
    • Beta Test Your Stuff!
  • Freelance, Contracts, Employment, etc.
    • Services Offered
    • Job Offerings
  • General Discussion
    • PHPFreaks.com Website Feedback
    • Miscellaneous

Find results in...

Find results that contain...


Date Created

  • Start

    End


Last Updated

  • Start

    End


Filter by number of...

Joined

  • Start

    End


Group


AIM


MSN


Website URL


ICQ


Yahoo


Jabber


Skype


Location


Interests


Age


Donation Link

  1. Hi. I'm not exactly new to PHP but I am brand new to this community. I have been PHP aware for about 5 years but in all that time the amount of coding I have actually done has been rather pathetic. I work for a company that is quite... insular, and secluded (their choice, not mine) from the wider developer community. As a result I only discovered PHP Frameworks about a year ago and feel quite behind the times. I am used to writing procedural PHP and not much else. I am here to hopefully broaden my horizons and get a better understanding of Frameworks, OOP, SQLi or PDO or database "unspecific" applications. When I first discovered PHP Frameworks about a year ago, my friend suggested I get started using CodeIgniter (that seems to be a lot of newbies' first choice!). I loved it, but after reading various rantings and ravings on the internet I decided that I should probably move on to something more "professional". That's when I came up against SF2 and almost cried myself to sleep every night. It made no sense to me. It still makes no sense to me. I gave up. After that I tried Laravel but couldn't even get going thanks to something called "Composer" which I still don't understand. I thought to myself, "I don't want to learn about dependencies at this stage, I just want to code". I gave up. Then another friend suggested I use PHP Slim. Another Framework. I tried to work with it but it seemed heavily dependant on knowing OOP, and I didn't have the first clue what I was doing. I gave up (are you sensing a pattern here?) So after that, I decided to try and learn the basics of OOP and how/why it was better than procedural and I have to say - I don't think it is. And I kind of hate it. I find it really confusing and not one person I have asked is able to tell me why OOP is better than procedural. They say "it just is". Sigh.... Then I decided to join PHP Freaks so I could vent my frustrations!
  2. Hello guys, i'm currently building my own cms, a personal project, and now im stucked on an error "Call to a member function query() on a non-object in.. please help after creating this function.. I know the db connection and everything else worked out because i have a similar function that works just without the switch or the numrow if statement. protected function _pageStatus($option, $id){ //check if page exists, if it does return the status, or return 404 switch($option){ case 'alpha' : $sql = "SELECT status FROM pages WHERE nick = '$id'"; break; case 'num' : $sql = "SELECT status FROM pages WHERE id = '$id'"; break; } if($result = $this->_db->query($sql)){ //<--- THE ERROR WAS ON THIS LINE. if($result->num_rows > 0){ while ($status = $result->fetch_object()) { return $status; } return $status; $result->close(); } else { return 404; } } }
  3. I can't find an explicit answer on this anywhere, but when you create a child class from an abstract class must you use ALL of the methods that are inside the abstract class in the new child class? Or are these methods just available to the child class to pick and choose?
  4. Newb here. My form works with sessions and the video loads etc, data submits, etc. all that is good. But i've gotten lost in the complexity of the build it seems and my html has become malformed I think. As a result each submission or page reload inserts another form inside the form inside the form etc etc etc. It some sort of weird looping madness or something. I'm very new to classes and how they work and i can't find where the madness is coming from. To duplicate the error, fill out the form and submit (the video won't play in firefox so use safari or chrome to test). I've been trying to resolve this for hours - i'm very lost in the complexity. <?php # '../' == sub-folder. use './' == root require '../inc_0700/config_inc.php'; #provides configuration, pathing, error handling, db credentials echo '<link rel="stylesheet" type="text/css" href="w05c09_gojiraIncidentReport.css">'; //END CONFIG AREA ---------------------------------------------------------- # Read the value of 'action' whether it is passed via $_POST or $_GET with $_REQUEST if(isset($_REQUEST['act'])){$myAction = (trim($_REQUEST['act']));}else{$myAction = "";} switch ($myAction){//check 'act' for type of process case "display": # 2)Display user's name! showObjects(); break; case "clear": # 3 Clear the session data clearObjects(); showForm(); break; default: # 1)Ask user to enter their name showForm(); } function showForm(){# shows form so user can enter their name. Initial scenario get_header(); #defaults to header_inc.php echo '<script type="text/javascript" src="' . VIRTUAL_PATH . 'include/util.js"></script> <script type="text/javascript"> function checkForm(thisForm){//check form data for valid info if(empty(thisForm.YourName,"Please Enter Your Name")){return false;} return true;//if all is passed, submit! } </script> <video id="bgVideo" preload="auto" autoplay="true" loop="loop" muted="muted" volume="0" poster="_bgGrfxs/bg_vidGlobe.jpg"> <source src="_bgVideo/bg_vidLoop.mp4" type="video/mp4"/> <source src="_bgVideo/bg_vidLoop.ogv" type="video/ogg"/> </video> <!-- This image stretches exactly to the browser width/height and lies behind the video--> <div id="bodyDummy"> <!-- <h3 align="center"">' . smartTitle() . '</h3>--> <br /> <br /> <br /> <br /> <br /> <br /> <form align="center" action="' . THIS_PAGE . '" method="post" onsubmit="return checkForm(this);"> <img width="10%" src="img_logo-panPacificDefenseCenter.png" alt="Kaiju Incident Reporter"/> <br /> <h2 style="color: #ff6d26;">Incident Report Form</h2> <br /> <!-- incWho? --> <br /> <b>Reporting Officer ID:</b><br /> <input type="text" name="incWho" placeholder="Please enter your full name here" /> <br /> <br /> <!-- incWhat --> <b><a id="orange" href="http://godzilla.wikia.com/wiki/Main_Page">Massive Unidentified Terrestrial Organism encountered:</a></b><br /> <select type="text" name="incWhat" data-placeholder="Select Incident Location..." class="chzn-select" multiple style="width:354px;" tabindex="40"> '; include 'ddlist-Kaiju.php'; echo '</select> <br /> <br /> <!-- incWhen = date of incident --> <b>Date of Incident:</b><br /> <input type="text" name="incWhen" placeholder="Please enter your full name here" /> <br /> <br /> <!-- incWhere --> <b>Incident Location:</b><br /> <select type="text" name="incWhere" data-placeholder="Select Incident Location..." multiple style="width:354px;" tabindex="111"> '; include 'ddlist-countriesInternational.php'; echo '</select> <br /> <br /> <!-- incWhy --> <b>Incident notes:</b><br /> <textarea name="incWhy" cols="54" rows="3" placeholder="Please enter any details you can recall of the incident - if incident is still occurring run" ></textarea> <br /> <br /> <!-- incScale --> <b>Rate the severity of the incident (0 to 5):</b> <br /> <br /> <input type="range" data-show-value="true" data-hightlight="true" data-popup-enabled="true" name="incScale" min="0" max="5" value="0" onchange="updateTextInput(this.value);"> <br /> <br /> <input id="go" type="submit" value="Go!"> </p> <input type="hidden" name="act" value="display" /> </form> <br /> <p style="#444"><i>Once you have completed your incident report, Run! For the love god man run, run for the hills and be safe!</i></p> '; get_footer(); #defaults to footer_inc.php echo '</div><!-- END bodyDummy -->'; } function showObjects() {#form submits here we show entered name //dumpDie($_POST); //if the session is not started, that could be a problem get_header(); #defaults to footer_inc.php if(!isset($_SESSION)){session_start();} echo "<br />"; if(!isset($_SESSION['kSession'])) {//if no session exists, create it $_SESSION['kSession']= array(); } //we need to add post data here $_SESSION['kSession'] [] = new incReport($_POST['incWho'], $_POST['incWhat'], $_POST['incWhen'], $_POST['incWhere'], $_POST['incWhy'], $_POST['incScale']); $totalScale = 0; foreach($_SESSION['kSession'] as $incReport)//loop thru each array item { echo $incReport; $totalScale += $incReport->incScale; } $totalReports = count($_SESSION['kSession']); $aveRating = $totalScale/$totalReports; echo '<div style="margin: auto; padding:0 10px; background-color:#ff6d26;width: 300px";><p style="color:white;">Average Incident Severity:</p> <h1 style="color:white;";>'; echo "$aveRating"; echo'</h1></div>'; if ($aveRating == 5){ echo '<p>Five: We suggest you make peace with this, your final moment.. enjoy the sunset before that giant foot comes down on you.</p>';} if ($aveRating == 4){ echo '<p>Four: The end is near, run man run, she isn\'t worth it, save yourse<p>lf.</p>';} if ($aveRating == 3){ echo '<p>Three: And your still there? Seriously?</p>';} if ($aveRating == 2){ echo '<p>Two: Take a picture, it will last longer. Now. Run for the hills!</p>';} if ($aveRating == 1){ echo '<p>One: Have you considered running?</p>';} if ($aveRating == 0){ echo '<p>Zero: This would be a good time to consider moving to a safer vantage point.</p></form></div><!--end dummy-->';} //get_footer(); #defaults to footer_inc.php //------end of work area-------// get_header(); #defaults to footer_inc.php if(!isset($_POST['incWho']) || $_POST['incWhat'] == ''){//data must be sent feedback("No form data submitted"); #will feedback to submitting page via session variable myRedirect(THIS_PAGE); } if(preg_match('[^A-Za-z0-9]', $_POST['incWho'])){//data must be alphanumeric only feedback("Only letters & numbers are allowed."); #will feedback to submitting page via session variable myRedirect(THIS_PAGE); } $myName = strip_tags($_POST['incWho']);# here's where we can strip out unwanted data } function clearObjects(){ //echo "clearing objects here"; if(!isset($_SESSION)){session_start();} unset($_SESSION['kSession']); feedback("session cleared"); } class incReport{ public $incWho = ""; public $incWhat = ""; public $incWhen = ""; public $incWhere = ""; public $incWhy = ""; public $incScale = ""; function __construct($incWho, $incWhat, $incWhen, $incWhere, $incWhy, $incScale){ $this->incWho=$incWho; $this->incWhat=$incWhat; $this->incWhen=$incWhen; $this->incWhere=$incWhere; $this->incWhy=$incWhy; $this->incScale=$incScale; } function __toString(){ static $kID = 1;//kaiju incident number $myReturn = '<video id="bgVideo" preload="auto" autoplay="true" loop="loop" muted="muted" volume="0" poster="_bgGrfxs/bg_vidGlobe.jpg"> <source src="_bgVideo/bg_vidLoop.mp4" type="video/mp4"/> <source src="_bgVideo/bg_vidLoop.ogv" type="video/ogg"/> </video> <div id="bodyDummy"> <br /> <br /> <br /> <br /> <br /> <br /> <form><p> Incident ID: kID00' . $kID ; //works $kID++; //iterate report $myReturn .= ' | Incident Reported by: ' . $this->incWho . ' ' ;//works $myReturn .= ' | Massive Terrestial Organsim Observed: ' . $this->incWhat . ' ' ;//shows where... $myReturn .= ' | Date of Incident: ' . $this->incWhen . ' ' ; //works $myReturn .= ' | Incident Location: ' . $this->incWhere . ' '; //shows what $myReturn .= ' | Incident Details: ' . $this->incWhy. ' '; // working $myReturn .= ' | Incident Severity: ' . $this->incScale . '</p> <p align="center"><a href="' . THIS_PAGE . '">File Report, then Run!</a> | <a href="' . THIS_PAGE . '?act=clear">Reset</a></p> ' ; return $myReturn; } }
  5. Hi Guys, I'm new to OOP. I've mastered some basic syntax, but am wondering about an issue of design. To clarify in this example, I'm simply looking to pull Team data from a Database (I've not included my db class (PDO wrapper) although I know it is working. Although I have seen this sort of method below in a book (I believe and on the net) and it does work, I cannot help thinking coupling the DB class so tightly with the Team Class isn't a great approach. Can anyone give me feedback as to whether my approach is valid? While I can see the negative issue of tight coupling (i.e. changes to any database method would require multiple changes in Team (as team methods were added), I cannot really see an alternative way of doing this? I guess this is an issue of a design pattern or more advance OOP. Can anyone suggest an alternative way and/or more reading on making the coupling looser while still achieving my objectives? Should, for example, all DB functionality in getName be done during implementation? I initally thought pushing all db related functionality inside a Team method was wise and the best way then to add further methods, i.e. getResults method would be similar to getName but obviously with a different query and processing afterwards inside Team, but now I wonder if all should be in the implementation, or is there another approach? Thanks in advance. // create team class class Team { private $db; private $team_name; private $team_id; private $result; // in constructor lets pass DB object public function __construct($db) { $this->db = $db; } //function to get team name public function getName($team_id) { $this->team_id = $team_id; $this->db->query("SELECT team_name, nickname, founded FROM club WHERE team_id=:teamid"); $this->db->bind(':teamid', $this->team_id); if ($result = $this->db->single()); { return $result[]; } } }// end class // Implementation $team_id=1; //passed from user input // First Create Db Object with correct passed variables $database = new Database($server,$db_type); // Invoke DB connect method $database->connect(); // Now create Team object, pass it database object $team = new Team($database); // call Team method $team_display = $team->getName($team_id); // close db $database->closedb();
  6. So I have this CMS that I have spent the last 5 years building and rebuilding and updating blah blah. It's a fairly extensive piece work and I am now looking at converting the entire system over to OOP. I am fairly new to OOP but understand the easy basics of it. I do fight with the concept of when to make a class and when to just make a normal function. I have many functions that I built specific to how my system works and some I suppose could be grouped into categories but then many others are just plain functions that only serve one purpose and may only be a few lines long. I will be using the spl_autoload_register() to load the classes as needed which is obviously much easier than including all the function pages that are needed. So for that reason I like the idea of making classes for everything but it just seems like more than is needed. So what I am looking for is some insight as to when and how to decide if a class should be made and whether to group functions by category to limit the amount of classes OR to just leave them as normal functions. Here is a example function for creating a thumbnail. I would guess that I could make a class called Thumb and put this in it, but what exactly would be the benefit of that based on the syntax of the function AND could you show me how you would convert this to OOP to make it worth while putting it in a class? // Creates a thumbnail function createThumb($img, $type, $dest = NULL, $xy = NULL) { if($type=="admin_product") { $thumb_width = $GLOBALS['admin_thumb_width']; $thumb_height = $GLOBALS['admin_thumb_height']; } elseif($type=="custom") { $thumb_width = ($dest !== NULL) ? $xy['x'] : (int)$_GET['width']; $thumb_height = ($dest !== NULL) ? $xy['y'] : (int)$_GET['height']; } $src_size = getimagesize($img); if($src_size['mime'] === 'image/jpg') {$src = imagecreatefromjpeg($img);} elseif($src_size['mime'] === 'image/jpeg') {$src = imagecreatefromjpeg($img);} elseif($src_size['mime'] === 'image/pjpeg') {$src = imagecreatefromjpeg($img);} elseif($src_size['mime'] === 'image/png') {$src = imagecreatefrompng($img);} elseif($src_size['mime'] === 'image/gif') {$src = imagecreatefromgif($img);} $src_aspect = round(($src_size[0] / $src_size[1]), 1); $thumb_aspect = round(($thumb_width / $thumb_height), 1); if($src_aspect < $thumb_aspect)//Higher { $new_size = array($thumb_width, ($thumb_width / $src_size[0]) * $src_size[1]); $src_pos = array(0, (($new_size[1] - $thumb_height) * ($src_size[1] / $new_size[1])) / 2); } elseif($src_aspect > $thumb_aspect)//Wider { $new_size = array(($thumb_height / $src_size[1]) * $src_size[0], $thumb_height); $src_pos = array((($new_size[0] - $thumb_width) * ($src_size[0] / $new_size[0])) / 2, 0); } else//Same Shape { $new_size = array($thumb_width, $thumb_height); $src_pos = array(0, 0); } if($new_size[0] < 1){$new_size[0] = 1;} if($new_size[1] < 1){$new_size[1] = 1;} $thumb = imagecreatetruecolor($new_size[0], $new_size[1]); imagealphablending($thumb, false); imagesavealpha($thumb, true); imagecopyresampled($thumb, $src, 0, 0, 0, 0, $new_size[0], $new_size[1], $src_size[0], $src_size[1]); //$src_pos[0], $src_pos[1] 3rd and 4th of zeros position on above line if($src_size['mime'] === 'image/jpg') { if($dest !== NULL) { imagejpeg($thumb, $dest, 95); } else { header('Content-Type: image/jpeg'); imagejpeg($thumb, NULL, 95); } } elseif($src_size['mime'] === 'image/jpeg') { if($dest !== NULL) { imagejpeg($thumb, $dest, 95); } else { header('Content-Type: image/jpeg'); imagejpeg($thumb, NULL, 95); } } elseif($src_size['mime'] === 'image/pjpeg') { if($dest !== NULL) { imagejpeg($thumb, $dest, 95); } else { header('Content-Type: image/jpeg'); imagejpeg($thumb, NULL, 95); } } elseif($src_size['mime'] === 'image/png') { if($dest !== NULL) { imagepng($thumb, $dest); } else { header('Content-Type: image/png'); imagepng($thumb); } } elseif($src_size['mime'] === 'image/gif') { if($dest !== NULL) { imagegif($thumb, $dest); } else { header('Content-Type: image/gif'); imagegif($thumb); } } imagedestroy($src); } Your insight is appreciated.
  7. Hey. Just recently got into developing with PDO and OOP, instead of the old MySQL_*, so I'm pretty new, and have some dumb questions. Right now I'm taking the first steps into making a blog (Nope, not a blogger - just need something to work on), and i came across a tutorial to create a database class. I have spend a little time on making such a class, and though I got it working just fine, I'm not really sure how useful and necessary it really is. Yeah, of course it saves you a couple of lines, but at the cost of getting used to using the class, instead of just raw PDO. Here is the class i just quickly made: <?php class database { private $host = DB_HOST; private $user = DB_USER; private $pass = DB_PASS; private $dbname = DB_NAME; public function __construct() { // Try connection or die. try { $this->db = new PDO('mysql:host='.$this->host.';dbname='.$this->dbname, $this->user,$this->pass); } catch(PDOException $e) { die($e); } } public function getColumn($sql, $params) { // Get value of a single row $query = $this->db->prepare($sql); $query->execute($params); return $query->fetchColumn(); } public function fetch($sql, $params) { // Return fetch $query = $this->db->prepare($sql); $query->execute($params); return $query->fetch(); } public function update($sql, $params) { // Update $query = $this->db->prepare($sql); $query->execute($params); } public function getRows($sql, $params) { // Return number of rows $query = $this->db->prepare($sql); $query->execute($params); return($query->rowCount()); } public function insert($sql, $params) { // Insert $query = $this->db->prepare($sql); $query->execute($params); } } ?> I know it can get way more optimized, advanced and usefull, but it's just a quick example. Is it just dumb to spend time on a database class, or is it worth the time? Any advice appriciated. Thanks in advande!
  8. Hi everyone, I am starting to learn PHP OOP and would like to know if you could help me understanding the scopes a little bit better. I have created the below code during my courses, but cannot work out how to reuse $this->total in another class. I have set the $total; to protected and was wishing to be able to use it in my second class but it returned an error. Any idea how I could use this variable in another class while set with the scope of Protected please? Thank you so much! Class Calculator{ public $number1; public $number2; protected $total; function setNumber1($int){ $this->number1 = (int) $int; } function setNumber2($int){ $this->number2 = (int) $int; } function Calculate(){ $this->total = $this->number1 + $this->number2; } function getResult(){ return $this->total; } } $Calculator = new Calculator(); $Calculator->setNumber1(5); $Calculator->setNumber2(10); $Calculator->Calculate(); echo $Calculator->getResult() . "<br>"; Class secondCalculator extends Calculator { $this->total = $this->number3 + $this->number4; } Ben
  9. Hello! i'm newer in OOP and I have made an website in PHP classic. I want to modify the website and to use OOP. For example in .htaccess I have RewriteRule ^index.html index.php [N] RewriteRule ^([a-zA-Z0-9-_]+).html$ index.php?pagina=$1 [L,QSA] RewriteRule ^([a-zA-Z0-9_-]+)/([a-zA-Z0-9-.\s]+).html$ index.php?pagina=$1&poll=$2 [L,QSA] RewriteRule ^([a-zA-Z0-9_-]+)/([a-zA-Z0-9-.\s]+)/([0-9-_]+)$ index.php?pagina=$1&paginaphoto=$2&id_photo=$3 [L,QSA] #RewriteRule ^([a-zA-Z0-9_-]+)/([a-zA-Z0-9-.\s]+)/([0-9-_]+)/?.jpg$ index.php?pagina=$1&paginaphoto=$2&id_photo=$3 [L,QSA] in index.php I have if ($_GET['pagina']=='katarina') { if ($_GET['paginaphoto'] == '') { echo '<td valign="top" style="border-left: 1px solid #cccccc; padding: 2px;">'; include('includes/katarina.php'); } elseif ($_GET['paginaphoto'] == 'photo') { echo '<td valign="top" style="border-left: 1px solid #cccccc; padding: 2px; border-right: 1px solid #cccccc; padding: 2px;">'; include('includes/photo.php'); } elseif (!empty($_GET['paginaphoto']) and $_GET['paginaphoto'] != 'photo') { echo '<META HTTP-EQUIV="Refresh" Content="0; URL=/katarina/index.html">'; exit; } } so in index.php I used the method GET to load the page katarina.php My problem is how could I change index.php if I would want to use OOP? I need some suggestions of you... Or maybe a good video on youtube or a good article on web. Thank you very much!
  10. I’m moving my code from Procedural to OOP and am having an issue trying to run a basic query. Looks like the connection to the DB is made, but I must not be fully understanding Objects / scope of Objects yet.. I’m trying keep it simple so I can test this out and understand it before updating my code. My instal thoughts are: 1. Get OOP class set up for DB Connection. MySQL first as that’s what I’m using now. Then config MSSQL and Oracle classes for easy integration. 2. Get simple queries working using a basic function file with PDO (Like current code). 3. Convert my function files to classes. I’ve separated my code to 3 function files (categories) for some organization. The files aren’t huge, but they do range from 150 lines to just over 1000. Below is the code I’m testing with. Pretty simple and I hope straight forward. I’ve also tried sending in $dbConn as a variable versus have it as a global variable in the function.. I’ve read that’s the better way. But if anybody has thoughts on that too I would love to hear opinions / recommendations. thanx Index.php - testing page: /** * Start Includes sections */ require_once("../includes/db_conn/MYSQL_database.php"); require_once("../includes/functions.php"); /** * End Includes sections */ /** * Check DB Connection */ if (isset($config)){ echo"<pre>"; print_r($config); echo"<pre>"; }else{ echo'<script type="text/javascript">window.alert("config not set")</script>'; } echo"<hr>"; //if (isset($database)){echo "Database opened"; } else {echo "Database not opened";} /** * If connected to DB load page * Else echo not connected */ if (isset($database)){ //echo "Database opened"; /** * Run query to verify working. */ $customers = cust_list($dbConn); echo "<pre>"; print_r($customers); echo "</pre>"; } else { echo "Database not opened"; } MySQLDatabase Class: class MySQLDatabase { /** * MySql Connect to DB */ private $host; private $dbname; private $username; private $password; public $dbConn; function __construct($config){ $this->host = ($config['host']); $this->dbname = ($config['dbname']); $this->username = ($config['username']); $this->password = ($config['password']); } private function open_connection(){ try{ //$this->connection = new PDO('mysql:host=' . $host . ';dbname=' . $dbname, $username, $password); $this->dbConn = new PDO('mysql:host=' . $host . ';dbname=' . $dbname, $username, $password); echo "<script type=\"text/javascript\">window.alert(\"Connection Made\")</script>"; }catch(PDOException $e){ echo 'ERROR Inside the open_connection funtion: ' . $e->getMessage(); } } } /** * Create object */ $database = new MySQLDatabase($config); Functions File (will be moved to a Class next): function cust_list($dbConn){ //global $dbConn; try{ /** * Prepare */ $cust_list = $dbConn->prepare("select * from customer"); /** * Bind */ /** * Execute */ $cust_list->execute(); /** * Fetch from array */ $cust_list_array = $cust_list->fetchall(PDO::FETCH_ASSOC); /** * Return */ return $cust_list_array; } catch(PDOException $e){ echo"Inside cust_list " . $e->getMessage(); } } When sending in $dbConn I get: Notice: Undefined variable: dbConn in /Users/aaronjk/localhost/base_sites/php_base/public/index.php on line 34 Fatal error: Call to a member function prepare() on a non-object in /Users/aaronjk/localhost/base_sites/php_base/includes/functions.php on line 12 When setting $dbConn as global inside the function I get: Fatal error: Call to a member function prepare() on a non-object in /Users/aaronjk/localhost/base_sites/php_base/includes/functions.php on line 12 From What I've read I "Call to member function prepare() on a non-object in.. " is because I need the global connection $dbConn set in the called function, but I thought I was doing that.
  11. Hey guys, I am learning some basic OOP rules and application right now. I was trying to understand setting a property inside of an object. $name = $_GET['user']; if(isset($name)){ class BankAccount{ public $balance = 3500; public function DisplayBalance(){ return $name . ' your Balance Currently is: ' .$this->balance; } public function Withdraw($amount){ $balance = $this->balance; if($balance < $amount){ $this->balance = 'Sorry you can\'t withdraw any funds right now, not enough to cover amount request of: $' .$amount . '. '; } else{ $this->balance = $this->balance-$amount; } } } So here i am trying to add an extra property into this class by grabbing the variable of $name, which is a dynamic string given from a user submit form. When i add public $user = $name; || $user = $name; I get an error, so my syntax is wrong So ultimately my question is, how do i correctly add the variable of $name into my class ? thanks guys,
  12. Hey guys, So long story short: I've got an assignment due in two weeks time. I'm going away next weekend so want to finish it before then. Problem is, we haven't covered all the necessary material in class yet, and would be expected to work on it over the final weekend it is due. I have a partner for this, but he is of no use in any IT subject. I would greatly appreciate if anyone could direct me to online tutorials or such, because I don't know how to do the following: construct the form so that the data can be written to a file in a way it can later be read, how to actually write this data to file, how to retrieve and read it. The assignment in short: Develop a form-based Web application that provides the following functionality: o Selection of a shape to develop o Creation of a collection of shapes o Various user queries of your own choice A system developed using object-oriented php which supports inter alia: o Various shapes o A collection of shapes o File I/O The pitiful excuse I have so far gives me this: http://www.aberdonia.com/aberdonia/web-dev/coursework/testing/showshapes.php
  13. I'm a beginner currently studying Object Oriented Programming. The code in question is quite long so I will just share the snippet that I can't understand. private $productlist = array(); public function addproduct($product){ $this->productlist[] = $product; } public function stockup(){ foreach($this->productlist as $product){ $product->addstock(100); } I'm sure that function addproduct adds product objects to the product list array. What does the foreach loop: foreach($this->productlist as $product) in the stockup function do? Does it take those values and store them back in $product?
  14. I have converted an old pagination function I've had for years to a class as I've recently started to learn OOP The problem is that it doesn't display any anything except the <ul></ul> I've tried returning a variable but it comes back empty. I know it's something to do with my variables but I can't see what class Pagination { private $total_pages; private $page; private $webpage; public function __construct() { $this->total_pages; $this->page; $this->webpage; } /** * This function is called whenever the there are several records to be displayed in the table * This saves the page extending further down the page creating a long list of results * when all the results can be spread across multiple pages */ public function pagination_one($total_pages, $page, $webpage) { // Maximum number of links per page. If exceeded, google style pagination is generated $max_links = 6; $h=1; if($this->page>$max_links) { $h=(($h+$this->page)-$max_links); } if($this->page>=1) { $max_links = $max_links+($this->page-1); } if($max_links>$this->total_pages) { $max_links=$this->total_pages+1; } $paging = ''; $paging .= '<div class="page_numbers"> <ul>'; if($this->page > "1") { $paging .= '<li class="current"><a href="/'.$this->webpage.'/1">First</a></li> <li class="current"><a href="/'.$this->webpage.'/'.($this->page-1).'">Prev</a></li> '; } if($this->total_pages != 1) { for ($i=$h;$i<$max_links;$i++) { if($i==$this->page) { $paging .= '<li><a class="current">'.$i.'</a></li>'; } else { $paging .= '<li><a href="/'.$this->webpage.'/'.$i.'">'.$i.'</a> </li>'; } } } if(($this->page >="1")&&($this->page!=$this->total_pages)) { $paging .= '<li class="current"><a href="/'.$this->webpage.'/'.($this->page+1).'">Next</a></li> <li class="current"><a href="/'.$this->webpage.'/'.$this->total_pages.'">Last</a></li>'; } $paging .= '</ul> </div>'; return $this->page; } } $paging = new Pagination(); var_dump( $paging->pagination_one(3, 1, 'news')); <?php class Pagination { private $total_pages; private $page; private $webpage; public function __construct() { $this->total_pages; $this->page; $this->webpage; } /** * This function is called whenever the there are several records to be displayed in the table * This saves the page extending further down the page creating a long list of results * when all the results can be spread across multiple pages */ public function pagination_one($total_pages, $page, $webpage) { // Maximum number of links per page. If exceeded, google style pagination is generated $max_links = 6; $h=1; if($this->page>$max_links) { $h=(($h+$this->page)-$max_links); } if($this->page>=1) { $max_links = $max_links+($this->page-1); } if($max_links>$this->total_pages) { $max_links=$this->total_pages+1; } $paging = ''; $paging .= '<div class="page_numbers"> <ul>'; if($this->page > "1") { $paging .= '<li class="current"><a href="/'.$this->webpage.'/1">First</a></li> <li class="current"><a href="/'.$this->webpage.'/'.($this->page-1).'">Prev</a></li> '; } if($this->total_pages != 1) { for ($i=$h;$i<$max_links;$i++) { if($i==$this->page) { $paging .= '<li><a class="current">'.$i.'</a></li>'; } else { $paging .= '<li><a href="/'.$this->webpage.'/'.$i.'">'.$i.'</a> </li>'; } } } if(($this->page >="1")&&($this->page!=$this->total_pages)) { $paging .= '<li class="current"><a href="/'.$this->webpage.'/'.($this->page+1).'">Next</a></li> <li class="current"><a href="/'.$this->webpage.'/'.$this->total_pages.'">Last</a></li>'; } $paging .= '</ul> </div>'; return $this->page; } } $paging = new Pagination(); var_dump( $paging->pagination_one(3, 1, 'news'));
  15. Hello folks, I think the question is rather self explicit. I need to create an object from which I can create instances during the life of my application. So I opted for a constructor object. I just don't know how to make it global so that all my scripts can have access to it. I have tried including it in a namespace without succes var myNamespace = { myConstructorObject:function(){ //Attributes and methods of my constructor go here } } Also tried this... var myNamespace = { function myConstructorObject(){ //Attributes and methods of my constructor go here } } In both cases, I create a new instance of my constructor like so var newInstance = myNamespace.myConstructorObject I also tired creating the constructor object as a global object outside of my namespace like so myConstructorObject = function(){ //Attributes and methods }
  16. I have a class for building forms and I want to upgrade it to handle Bootstrap. I'd like to use my current methods to build the Bootstrap elements, but I don't want all of this new Bootstrap code cluttering up my current Forms class, so I'd like to put it into its own class in a separate file. Below is a very simple example of what I'm trying to do. Obviously this doesn't work and the code is wrong, however, from this you can hopefully see what I'm trying to accomplish. <?php class Forms { public function input_text($name) { return '<input type="text" name="'.$name.'">'; } } class Bootstrap { public function bootstrap_input_text($name) { $return = '<div class="control-group">'; $return .= '<label class="control-label" for="'.$name.'">First name</label>'; $return .= '<div class="controls">'; $return .= $this->Forms->input_text($name); $return .= '</div>'; $return .= '</div>'; return $return; } } $form = new Forms(); echo $form->bootstrap_input_text('fname');
  17. I have been learning php for just over a year now, and am getting pretty good at procedural coding. But now I can feel it is time to take it to the next step and be all about OOP. I have tried to learn some MVC, but at this stage I feel it is a bit too advanced for me, and am not quite ready for such a jump. So I was wondering what is a more basic design pattern, to just get started with OOP and getting used to classes. So starting out, how is this usually done? Does each new page have its own class, e.g. products.php, and classes/products.php, and the product.php will just call various methods from the class? Or would there just be a library folder for different classes, and you include whichever class you need to use at a time? Should there be a general class or classes that are called on every page? I guess I am asking what would be a good basic design pattern or structure to get strated with OOP?
  18. Hello, I've followed the whole series of Log in and registration system on the phpacademy channel on Youtube: http://www.youtube.com/playlist?list=PLE134D877783367C7 After reading some comments and doing some research I found that it uses md5 and old mysql_ function, which for some reason are 'deprecated' or not secure. I'm still not sure. Also, after doing some searching I came across: http://www.sunnytuts.com/article/login-and-registration-with-object-oriented-php-and-pdo which is another tutorial that is quite similar to the one on phpacademy, but it uses PDO and Object oriented programming and bcrypt instead of md5(). The problem is that I don't know OOP and I use procedural programming. So is it worth learning OOP and using bcrypt() instead of md5() or PDO instead of mysql? I mean, am I ok with using the code from phpacademy, or do I need to follow the other one and also learn OOP. Thank you very much.
  19. I've got a class method that is working fine on my localhost but when I included on the website im working on it aint working, and I see that the site only requires static call. I use to call like this, and this is working fine: $result = $this->Class->method(0); $result->methodFromAnotherClass(); But on the modified framework that right now I'm using I ain't allowed to use that kind of calling. It must be a static call so I use $result = Class::method(0); but when I use to call the other method like: $result->methodFromAnotherClass(); It give's me an error. Anyone can suggest how to do it?
  20. I think I'm starting to wrap my mind around how to work with OOP - Objects and Arrays I have starting a small test php file that I'm doing testing on. Here's my main file <?php require('includes/Connect.MySQL.Class.php'); ?> <?php require('includes/TopicFileClass.php'); ?> <?php $data = array(); // New instance/modifier of class MemberTopic $topic = new MemberTopic($data); // Retrieve topics from mysqli database $topic = $topic->retrieve_record(); //print_r($topic); ?> <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>Object Oriented Programming</title> </head> <?php ?> <body> <?php foreach ($topic as $key=>$record) { // Loop through the Array to pull out the objects(records)?> <h1><?php echo $record->blog_name; // Display the Title of the Blog ?></h1> <p><?php echo $record->content; // Display the Content of the Blog ?></p> <?php } // Closes the foreach loop ?> </body> </html> An here is where I retrieve my data <?php require_once ("Connect.MySQL.Class.php"); class MemberTopic extends ConnectMySQLClass { protected $threads = array(); protected function main_record() { $database = parent::connect(); //Connects to the mysqli Database $query = "SELECT * FROM pages ORDER by id"; $result = $database->query($query); while ($page = $result->fetch_array(MYSQLI_ASSOC)) { $this->threads[] = (object) $page; } /* free result set */ $result->free(); //print_r($this->threads); return $this->threads; } public function retrieve_record() { //return $records = $this->assign_topic_record(); return $this->main_record(); } } My questions is there a way to make it so I have each object tied to a user name instead of a number? I tried doing $this->threads[$page['username']] = (object) $page; which only worked partially for it skip a few records(objects). If there isn't a way of doing it, it's no big deal for this has simplified my code a lot and makes it so much easier following what the code is doing. Thanks John
  21. Hey, I am new to PHP and I'm trying to understand this tutorial that instanicates a row, and assigns it to a $object[] array through a method called find_by_sql. There is another method that is called find_by_id that uses the find_by_sql method, the difference is it just finds the array through an ID. My question is why does the find_by_id method returns the result set using an array_shift? Below is the code. Any help will be highly appreciated! :happy-04: The Class starts with the user attributes.. they get assigned by the instantiate method below. class User { //Object attributes are below public $id; public $username; public $password; public $first_name; public $last_name; Below is the find_by_sql and find_by_id method. /* 1) The following method below does the SQL finding based on an arguement that i passed in 2) It then preforms a fetch array on the result set and instantiates it with the instantiate method below and assigns it to the $object_array */ public static function find_by_sql($sql="") { global $database; // Brings in the $database instanitated object. $result_set = $database->query($sql); // Runs the query on the $sql argument $object_array = array(); // Initilizes an object_array while ($row = $database->fetch_array($result_set)) { $object_array[] = self::instantiate($row); // Take the instanciated row and assignes it to $object_array } return $object_array; } public static function find_by_id($id=0) { // Takes an ID as an argument $result_array = self::find_by_sql("SELECT * FROM users WHERE id={$id} LIMIT 1"); return !empty($result_array) ? array_shift($result_array) : false; // Why does it take the first element out of the array ??? } Below is the instantiate method that instantiates a row and assigns it to the attriubutes above private static function instantiate($record) { // Could check that $record exists and is an array $object = new self; // Instanciates the user calss to $object // Simple, long-form approach: // $object->id = $record['id']; // $object->username = $record['username']; // $object->password = $record['password']; // $object->first_name = $record['first_name']; // $object->last_name = $record['last_name']; // More dynamic, short-form approach: foreach($record as $attribute=>$value){ if($object->has_attribute($attribute)) { // the has_attribute is a function I had to write below the checks if the attributes are in the object first. $object->$attribute = $value; } } return $object; } private function has_attribute($attribute) { // get_object_vars returns an associative array with all attributes // (incl. private ones!) as the keys and their current values as the value $object_vars = get_object_vars($this); // We don't care about the value, we just want to know if the key exists // Will return true or false return array_key_exists($attribute, $object_vars); } }// end of user class
  22. I am tring to learn about PDO people have said its easy and the best way to interact with the database, but im not finding it easy. can any help? Should i have my connection in its own class and extend it to the rest of my classes or should i use a global variable to connect? or is there another way better? i read up about the try and catch method not very good either. my database is mysql
  23. Hey, I am creating a session class for one of my ecommerce application. Below is the class I have created. I was wondering how would I go about creating a message for the session being expierd and a message if the session was not found? Also does this class look correct? Thanks class Session { public $mycart; public $store_name; public $discount_session; function __construct() { session_start(); $this->store_name(); } function store_name() { if(isset($_SESSION['store_name'])) { $this->store_name = $_SESSION['store_name']; } } function my_cart() { if(isset($_SESSION['my_cart'])) { $this->mycart = $_SESSION['store_name']; } } function discount_session() { if(isset($_SESSION['discount_session'])) { $this->discount_session = $_SESSION['discount_session']; } } } $session = new Session;
  24. Hey, I am new to OOP, and I am trying to echo out the username with a static call. When i tried to get the call, I get nothing displayed on my browser. Not even an error message? Below is the static call I am making . $found_user = User::find_by_id(; echo $found_user['username']; Here is my user class. In my user class i have included my database class. I have instaniated my database class and assigend it to the $database variable <?php // THe user class preforms all its FIND methods. require_once("database.php"); class User { public function find_all () { global $database; $sql = "SELECT * FROM users "; $result_set = $database->query("SELECT * FROM users "); return $result_set; } public function find_by_id($id=0) { global $database; $result_set = $database->query("SELECT * FROM users WHERE id={$id}"); $found = $database->fetch_array($result_set); return $found; } } ?> Below is my database class.... <?php require_once("config.php"); class MySQLDatabase { private $connection; public $last_query; function __construct() { $this->database_construct(); } function database_construct() { $this->connection = mysql_connect(DB_SERVER, DB_USER); if(!$this->connection) { die ("Database connection could not be made"); } else { $db_select = mysql_select_db(DB_NAME, $this->connection) ; if(!$db_select) { die ("The database could NOT be selected"); } } } function close_connection() { if(isset($this->connection)) { mysql_close($this->connection); unset($this->connection); } } public function fetch_array($result_set) { mysql_fetch_array($result_set); return mysql_fetch_array($result_set); } public function num_rows($result_set) { mysql_num_rows($result_set); return mysql_num_rows; } public function insert_id() { return mysql_insert_id($this->connection); } public function affected_rows() { return mysql_affected_rows($this->connection); } public function query($sql){ // this function preforms a mysql query $this->last_query = $sql; $result = mysql_query($sql, $this->connection); $this->confirm_query($sql); return $result; } private function confirm_query($result_set) { if(!$result_set) { $output = "Database query failed" . mysql_error() . "<br />"; $output .= "The last query that was made was {$this->last_query}" ; die ($output); } } } //end of class MySQLDatabase { $database = new MySQLDatabase(); $db =& $database; ?>
  25. I am trying to access a variable through a class, and can't work out how to this. class test { function method() { if (isset({$testing})) { echo {$testing}; } } } $testing = 'it works'; $thetest = new test; $thetest->method(); Is this even possible, or have I got very confused?
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.