Jump to content
Stef's Coding Community
akurtula

oo php - reading functions

Recommended Posts

on my second year at university i worked on php and managed to create a shopping cart system, at the time i was not using object orientated. Since then i needed to deviate my focus on other programing languages (as part of the curriculum)

 

anyway, i am trying to play around with oo php and i thought i would try and create few function and class around the code i already have (from the shopping card)

 

i have create this class

class cart{
   function  __construct() {
       $dbc = mysql_connect("localhost","root","") OR die('Could not connect: ' . mysql_error());
mysql_select_db("agile") OR ('coul not select db : '. mysql_error());
   }
var $image; var $item; var $desk; var $price; var $qu;
public  function read(){
    if ($_GET['me'] == true) {
$cat = $_GET['me'];
}else{
$cat = "price";
}
$query = "SELECT * FROM kurtula_shop where quantaty > '0' ORDER BY $cat ";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result,MYSQL_ASSOC))
{
$this->image = $row[image];
$this->item = $row[item];
$this->desk = $row[description];
$this->price = $row[price];
$this->qu = $row[quantaty];
} 
return $this->desk;
}}

 

as you can see at the moment i am only trying to return the descriotion that is within the database (there is more then one record/item in the database)

 

now on i am trying to display each record in the view page, and i am using the following code:

 

$cart = new cart();
echo $cart->read();

 

however this only displays the first record on the DB (even though there are more, and i am using the while loop within the class.

 

i tried to using the following code (but it gives an error)

$cart = new cart();
foreach( $cart->read() as $product){
echo $product->read();
}

 

i would really appreciate any help you could give me.

Share this post


Link to post
Share on other sites

It's a goog practice to set link_identifier of MySQL connection :

mysql_select_db("agile", $dbc) OR ('coul not select db : '. mysql_error());

 

About your learn and write you code in oop, you have to read more about tendency and practice in PHP OOP.

Everything about these things : how to declare classes, methods, members, what types exist, design patterns in OOP ...

About your code you can try to organize some classes structure based on your logic and requirements.

Just foe example :

class Config
{
 const DB_HOST     = "localhost";
 const DB_USERNAME = "username";
 const DB_PASSWORD = "pass";
 const DB_NAME     = "dbname";
}

class Cart{

 public $image;
 public $item;
 public $desk;
 public $price;
 public $qu;

 public  function read( MysqlQuery $resObj ){

   if( $resObj instanceof MysqlQuery ) {
     while ($row = mysql_fetch_array($resObj->getResult(), MYSQL_ASSOC)) {
       $this->image[$row['itemId']]  = $row['image'];
       $this->item[$row['itemId']]   = $row['item'];
       $this->desk[$row['itemId']]   = $row['description'];
       $this->price[$row['itemId']]  = $row['price'];
       $this->qu[$row['itemId']]     = $row['quantaty'];
     }
   }
 }
}

class DatabaseConnection extends Config
{
  /**
   * A static property to hold the single instance of the class
   */
  private static $instance;
   /**
    * The constructor is private so that outside code cannot instantiate
    *
    */
   private function __construct() {

       $dbc = mysql_connect(parent::DB_HOST , parent::DB_USERNAME , parent::DB_PASSWORD );
       mysql_select_db( parent::DB_NAME, $dbc );

       if ( mysql_error() || mysql_errno()) {

         throw new Exception('Databse error: '.mysql_errno().' - '.mysql_error());
       }
   }

   /**
    * All code that needs to get and instance of the class should call
    * this function like so: $db = Database::getInstance();
    */
   public function getInstance()
   {
       // If there is no instance, create one
       if (!isset(self::$instance)) {
           $class = __CLASS__;
           self::$instance = new $class;
       }
       return self::$instance;
   }
   /**
    * Disallow cloning
    *
    */
   private function __clone() {}
}

class MysqlQuery {

 protected $_result;

 public function __construct(){
   $this->_result  = "";
 }

 public function query($sql) {

      $this->_result = mysql_query($sql);

      if ( mysql_error() || mysql_errno()) {

         throw new Exception('Databse error: '.mysql_errno().' - '.mysql_error());
      }
 }

 function setResult($value) {
     $this->_result = $value;
 }
 function getResult(){
     return $this->_result;
 }

 /**
  * here you can write some your query function which you use lots of times
  */
}
/**
* index.php
*/
$dbc      = new DatabaseConnection();
$sqlQuery = new MysqlQuery();

if ($_GET['me'] == true) {
       $cat = mysql_real_escape_string(trim($_GET['me']));
}else{
       $cat = "price";
}

$sqlQuery->query("SELECT * FROM kurtula_shop where quantaty > '0' ORDER BY $cat");

$card = new Cart();
$card->read($sqlQuery);
foreach ( $card->desk as $key => $value) {
   print_r("For item $key - desc = $value");
}

 

In this loop

while ($row = mysql_fetch_array($result,MYSQL_ASSOC))
{
$this->image = $row[image];
$this->item = $row[item];
$this->desk = $row[description];
$this->price = $row[price];
$this->qu = $row[quantaty];
} 

you have to put values in array because, you overwrite the value

in

$this->desk = $row[description];

for evaryone row which query retrn.

 

What exactly error you receive?

Share this post


Link to post
Share on other sites

If you are switching from a function based approach and going to implement a OOP standard of coding, I suggest you ditch the old function based mysql functions and switch over to OO based functions instead, namely using the mysqli library.

Share this post


Link to post
Share on other sites

thanks pollux i am going to take a look at the code;

 

i am pretty bad at the terminology and because i could not work on php for such long time, i feel as if i'm starting all over (but i hope everything i have learned before will come to surface soon)

 

so Krillz - your comment sounds interesting and familiar , as i heard about mysqli (and recently seen it in a job advertisement ) but i dont know what that it

 

to be honest I would really benefit if someone could recommend by some books to build up on the excellent video intro on OO php (that is on killerphp site)

 

as i just about to graduate, i have planed to take the three months summer time to just built up on my portfolio and hopefully be able to have really good work to present to the employers

 

thanks guys

Share this post


Link to post
Share on other sites

mysqli is the new mysql library for php using an object oriented solution. This was you have your mysqli object with class members you can utilize in any OOP standard fashion. And to be honest if you know the old mysql commands and have done object oriented code this will be just a matter of typing it out slightly differently.

 


// creating a new object of the type mysqli, you automatically get a refference to the connection stored in your refference variable.
$conn = new mysqli('host', 'user', 'pass', 'database');
// this way you can do the usual stuff but with a OO syntax.

$result = $conn->query('SLQ QUERY');

if( $result && $result->num_rows > 0 ) {
 // do what you need
}

$conn->close();

 

Of course PHP being friendly to people coming from other languages you will find different functions/ways that seem different but do the same thing when it comes down to it. Also a lot functions are static not requiring an init of the object to use which can get useful at times. And PHP being PHP I would say you can find anything and everything a long with good code examples and remarks by users in the comments.

Go to www.php.net/mysqli and spend 1-2 hours to get used to it then your set to go.

Share this post


Link to post
Share on other sites

I am sorry, but is there any other resource where I can learn about mysqli, as the php documentation at php.net seems to be a bit confusing (in fact i always struggle to get anything useful out of that manual, is that normal?)

Share this post


Link to post
Share on other sites

I had some trouble with the MySQLi documentation myself. It isn't as clear as it could be. In case it helps, I did a tutorial on PHP/MySQLi. The code is here: http://www.killersites.com/community/index.php?/topic/3064-basic-php-system-view-edit-add-delete-records-with-mysqli/ and the couple part screnncast is available in the KillerSites University ( http://www.killersites.com/university - subscription required) within PHP > PHP CRUD Videos.

 

I really would suggest that you persist with learning MySQLi (or PDO: http://php.net/manual/en/book.pdo.php) It's support for prepared statements means it is significantly more secure from MySQL injection and other security risks.

Share this post


Link to post
Share on other sites

falkencreative - thanks

 

just my looking at your tutorial, i get the krillz said

mysqli is the new mysql library for php using an object oriented solution
.

 

i gues i hsve a lot to learn.

 

by the way, is there any tutorials on oo php (that goes beyond the killer oo php tutorials - as they are really good, but as you can see, i'm finding it hard to build upon the examples.

 

once again thanks for the tutorial

Share this post


Link to post
Share on other sites

Hi,

 

We have a couple of tutorials that will help you when it comes to learning more about PHP OOP. Our shopping cart tutorial is kinda of a cross between old style procedural PHP and OOP. We went that way to try and bridge the PHP styles.

 

Then our Advanced PHP course goes much deeper into .. well, advanced PHP. There are plenty of free sample videos on that page - so check it out.

 

In the killersites university, we have a bunch of PHP videos and many more to come.

 

Stefan

Share this post


Link to post
Share on other sites

thanks stefan,

 

i guess my over all questions are answered

 

i will buy the advanced videos soon - now the CD version, does it have anything extra, so if i chose to "download now" - would i be missing anything form the CD

 

thanks to you all - you're great :)

Share this post


Link to post
Share on other sites

i finally had a play with the code pollux wrote, it giving me the error of

 

Access denied for user 'ODBC'@'localhost' (using password: NO) in D:\xampp\htdocs\000.SERVICES\001.PHP\projects\001.object_orientated\cart.php\cart_lib.php on line 82

 

line 82 refers to this:

$this->_result = mysql_query($sql);

 

and as far as i know the problem is in this:

 private function __construct() {

       $dbc = mysql_connect(parent::DB_HOST , parent::DB_USERNAME , parent::DB_PASSWORD );
       mysql_select_db( parent::DB_NAME, $dbc );
//...

 

now when i hover over the $server, $user and password; a pop-up (the little hints) come up saying they are equal to null

 

i tried to search the error in google and it says that the configuration details are not set

 

but i did change them:

 

class Config{
 const DB_HOST     = "localhost";
 const DB_USERNAME = "root";
 const DB_PASSWORD = "";
 const DB_NAME     = "agile";
}

 

though i even tryed to enter the config info directly:

 

$dbc = mysql_connect("localhost" , "root" , "" );

 

but still the same error

 

hope you can help

Share this post


Link to post
Share on other sites

i finally had a play with the code pollux wrote, it giving me the error of

 

Access denied for user 'ODBC'@'localhost' (using password: NO) in D:\xampp\htdocs\000.SERVICES\001.PHP\projects\001.object_orientated\cart.php\cart_lib.php on line 82

 

line 82 refers to this:

$this->_result = mysql_query($sql);

 

and as far as i know the problem is in this:

 private function __construct() {

       $dbc = mysql_connect(parent::DB_HOST , parent::DB_USERNAME , parent::DB_PASSWORD );
       mysql_select_db( parent::DB_NAME, $dbc );
//...

 

now when i hover over the $server, $user and password; a pop-up (the little hints) come up saying they are equal to null

 

i tried to search the error in google and it says that the configuration details are not set

 

but i did change them:

 

class Config{
 const DB_HOST     = "localhost";
 const DB_USERNAME = "root";
 const DB_PASSWORD = "";
 const DB_NAME     = "agile";
}

 

though i even tryed to enter the config info directly:

 

$dbc = mysql_connect("localhost" , "root" , "" );

 

but still the same error

 

hope you can help

 

I assume you are using wamp or some other ready to go server, where the standard mysql user has no pass set.

Go into phpmyadmin and add a password to the root user, or preferably create a new user that you will use in development with a password and use that instead.

Share this post


Link to post
Share on other sites

i added a password to root user - but i get the same error ".. (using password:NO) ..."

 

i also tried to add a new user with all privileges, and still i get the exact same error

 

and i am using xampp as a local server

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

×
×
  • Create New...