Jump to content
Killersites Forums

OOPS - MySQL connecting and fetching data.


russellharrower
 Share

Recommended Posts

Hi guys, I have looked everywhere with NO success, I don't understand any of these frameworks that are already out,

and i have read all the killerphp.com documents and watch all the videos that i can find about OOP and still cant find what i need.

 

I am new to OOP but know PHP, if someone can PLEASE help me out, and show me an example on how to use OOP to connect to MySQL that would be GREAT!

 

PLEASE HELP

 

Thanks

Link to comment
Share on other sites

Hi guys, I have looked everywhere with NO success, I don't understand any of these frameworks that are already out,

and i have read all the killerphp.com documents and watch all the videos that i can find about OOP and still cant find what i need.

 

I am new to OOP but know PHP, if someone can PLEASE help me out, and show me an example on how to use OOP to connect to MySQL that would be GREAT!

 

PLEASE HELP

 

Thanks

Hi, I just created an object today, If you like I can share it with you. My object just does something simple like connect to mysql, select any database that you want to work with. Let me know if you interested this.

Quyen,

Link to comment
Share on other sites

Hi,

You are welcome, i am not sure this will be a good example for you but I hope so.

 

DBObject.php

 

<?php 
   /* Created by Quyen. 11 July 2009
    *    Email : cuncon.it@gmail.com
    * DBObject.php
    */

   /* 
    * I just create a very simple class called DBObject 
    */
   class  DBObject{
       /////////////////////////////////////////////////
       // PRIVATE PROPERTIES  
       /////////////////////////////////////////////////
       private $hostname, $username, $password, $db_name, $con;

   /**
      * Constructor
      * @param String $hostname,$username,$password,$db_name. 
      * All information we need to provide whenever connect to db.
      */
       public function __construct($hostname,$username,$password,$db_name){
           $this->hostname = $hostname;
           $this->username = $username;
           $this->password = $password;
           $this->db_name = $db_name;
       }

   /**
      * Connect to MySQL.
      * @return void
      */
       public function connectToMySQL(){
           $this->con = mysql_connect($this->hostname,$this->username,$this->password);
           if($this->con){
               echo "
Connected sucessfully to MySQL .
";
           }
           else{
               die( "
Could not connect to MySQL" . mysql_error() . ".
");
           }
       }
   /**
      * Select a database you will work with.
      * @return void
      */        
      public function selectDB(){
           $result = mysql_select_db($this->db_name,$this->con);
           if($result){
               echo "
Connected sucessfully to database ' ".$this->db_name." ' .
";
           }
           else{
               die( "
Could not connect to database ' ". $this->db_name. " '  ".mysql_error() . ".
");
           }
       }

   /**
      * Later you can write some methods  to set and get value of Fields (Variables).
      * @
      */    
      public function setDBName()    {}

   /**
      * Show a simple message.
      * @return void
      */        
       public function showMessage(){
           echo "

Now you can execute any queries or create a database or do what ever you like (*_*)....

               Have a good time!
           ";
       }

   }
?>

 

CreateObject.php

 

<?php 
   //Include DBObject.php file 
   include ("DBObject.php");

   //Create objects from DBObject class.
   $myObj = new DBObject("localhost","root","","mysql");
   $anotherObj = new DBObject("localhost","root","","information_schema");

   //Call methods of objects.
   $myObj ->connectToMySQL();
   $myObj ->selectDB();
   //$myObj ->showMessage();

   $anotherObj->connectToMySQL();
   $anotherObj ->selectDB();
   $anotherObj ->showMessage();
?>

 

Have a nice day!

Quyen,

Link to comment
Share on other sites

hi Quyen,

 

I get what you are doing, but just one last question if you can help that would be great.

how to i fetch data from the database using oops?

 

like say i need to show the table called "yum"

 

inside the table "yum" it has two rows with data, under the row called "fruit"

1 - apple

2 - banana

 

But i when i run the select fruit from yum;

it prints both of the fruit - "applebanana"

what i need it to do is give each fruit a class or a way i can call it by

 

$class->fruitone;

$class->fruittwo;

 

Can you help there?

Link to comment
Share on other sites

hi Quyen,

 

I get what you are doing, but just one last question if you can help that would be great.

how to i fetch data from the database using oops?

 

like say i need to show the table called "yum"

 

inside the table "yum" it has two rows with data, under the row called "fruit"

1 - apple

2 - banana

 

But i when i run the select fruit from yum;

it prints both of the fruit - "applebanana"

what i need it to do is give each fruit a class or a way i can call it by

 

$class->fruitone;

$class->fruittwo;

 

Can you help there?

 

Did you mean that:

1. You want to select your data from table called 'yum'. This table has two fields: 'id' and 'fruit'.

2. You need to select all the records from the table above, and fill up them in a table? like

 

id name

 

1 banana

2 apple

3 warter melon

.. ...................

 

Is that what you mean?(*_*)

Quyen,

Link to comment
Share on other sites

Hi again,

 

I just finished it, have look and I hope this could help you a bit (*_*).

Notes: In this database, I created a table called 'yum' , 2 fields are 'id' and 'name'. When you test this example, try to created a database has the same my database information. If not then you will get some errors. OR you can set the database name and table name in the code below.

 

DBObject.php

>
<?php 
   /* Created by Quyen. 11 July 2009
    *    Email : cuncon.it@gmail.com
    * DBObject.php
    */

   /* 
    * I just create a very simple class called DBObject 
    */
   class  DBObject{
       /////////////////////////////////////////////////
       // PRIVATE PROPERTIES  
       /////////////////////////////////////////////////
       private $hostname, $username, $password, $db_name, $con, $table_name;

   /**
      * Constructor
      * @param String $hostname,$username,$password,$db_name. 
      * All information we need to provide whenever connect to db.
      */
       public function __construct($hostname,$username,$password,$db_name){
           $this->hostname = $hostname;
           $this->username = $username;
           $this->password = $password;
           $this->db_name = $db_name;
       }

   /**
      * Connect to MySQL.
      * @return void
      */
       public function connectToMySQL(){
           $this->con = mysql_connect($this->hostname,$this->username,$this->password);
           if($this->con){
               echo "
Connected sucessfully to MySQL .
";
           }
           else{
               die( "
Could not connect to MySQL" . mysql_error() . ".
");
           }
       }
    /**
      * Select a database you will work with.
      * @return void
      */        
      public function selectDB(){
           $result = mysql_select_db($this->db_name,$this->con);
           if($result){
               echo "
Connected sucessfully to database ' ".$this->db_name." ' .

";
           }
           else{
               die( "
Could not connect to database ' ". $this->db_name. " '  ".mysql_error() . ".
");
           }
       }
    /**
      * Get back the name of database.
      * @return String $db_name
      */        
       public function getDBName(){
           return $this->db_name;
       }

    /**
      * Set table name that you want to select data from.
      * @return void
      */        
       public function setTableName($table_name){
           $this->table_name = $table_name;
       }        

    /**
      * Get back the name of a table
      * @return String $table_name
      */    
       public function getTableName(){
           return $this->table_name;
       }

    /**
      * View data of a table
      */    
       public function viewTableData($db_name,$table_name){
              mysql_select_db($db_name);
           $sql = "Select * from $table_name";
           $result = mysql_query($sql);
           $count_fields = mysql_num_fields($result); 
           $count_rows = mysql_num_rows($result);
           $index = 0;
           echo "
</pre>
<table border="1" width="50%">This is '$table_name' table dataID Fruit name".$row['id']."".$row['name']."</table>
<br>           "; <br>       }<br><br>   /**<br>      * Show a simple message.<br>      * @return void<br>      */        <br>       public function showMessage(){<br>           echo "<br><br><br>               I don't have much time, because I have something to do tomorrow, then if you<br>               have some time, read some more about MVC (Model - View - Control) to organize your <br>               object better.For now I just put all them together. Work more on your database (*_*)....<br><br>               Have a good time!<br><br>           ";<br>       }<br><br>   }<br>?&gt

 

CreateObject.php

 

<?php 
   //Include DBObject.php file 
   include ("DBObject.php");

   //Create objects from DBObject class.
   $myObj = new DBObject("localhost","root","","mydb");

   //Call methods of objects.
   $myObj ->connectToMySQL();
   $myObj ->selectDB();

   $myObj ->setTableName("yum");
   $myObj ->viewTableData($myObj->getDBName(),$myObj->getTableName());
   $myObj ->showMessage();
?>

 

If you have any question, just email me at cuncon.it@gmail.com. or leave your reply in this forum. Goodnight.

Quyen,

Edited by quyen
Link to comment
Share on other sites

Thanks Quyen, Just wondering the following:

 

Say i want to have one file that handles connecting to the database. - opendb.php

and one that closes the database - closedb.php

 

is that possible, and how?

 

Then say i want another a page to handle MYSQL. - fruitdb.php

How would one go about that?

Edited by russellharrower
Link to comment
Share on other sites

Thanks Quyen, Just wondering the following:

 

Say i want to have one file that handles connecting to the database. - opendb.php

and one that closes the database - closedb.php

 

is that possible, and how?

 

Then say i want another a page to handle MYSQL. - fruitdb.php

How would one go about that?

 

Hi,

Sorry I haven't replied to you yet! Cause I just take a look at CSS forum(*_*).

About your question:

- To open a connection to a database or close this connection is not complicate, right? But the thing is how to organize your coding in php file?

For me I won't put them in a seperate files. Cause close or open is methods (behaviors) of objects. With mysql_connect() and mysql_close() Why don't you write some methods like this:

 

function connectToMySQL(){

//You write your code here

}

 

function closeConnection(){

//Do something else here and at the end you can

mysql_close();//For example

}

 

And then:

Whenever you create a object from the class above, after you are done everything like select a database, execute sql queries,....After you're done you just need a line of coding like:

objectName.closeConnection();

 

Notes: For me, I don't care much about number of php files, I care more about what my object can do? Is it enough or need some more fields, methods,.... If your object is perfect, that mean you did a great job (*_*). Don't worry about how many php file you going to create, lets care about how many object do u need in your project? And all fields & methods of your objects are enough or not?

 

And one more thing I guess you need to read some more is about OOP. Cause whenever you want your object do something, you will go and create a object and then call the suitable method of the object for it.

All the methods you create in your projects are called by objects (*_*).

 

I am not sure if this could help u! but still hope that you understand what i mean!

Let me know if you need something!

Quyen,

Link to comment
Share on other sites

Just another question, and an objectName a class name? $DBConnect.closeConnection();

 

Would something like this work?

 

class  DBConnect{
       /////////////////////////////////////////////////
       // PRIVATE PROPERTIES  
       /////////////////////////////////////////////////
       private $hostname, $username, $password, $db_name, $con;

   /**
      * Constructor
      * @param String $hostname,$username,$password,$db_name. 
      * All information we need to provide whenever connect to db.
      */
       public function __construct($hostname,$username,$password,$db_name){
           $this->hostname = $hostname;
           $this->username = $username;
           $this->password = $password;
           $this->db_name = $db_name;
       }

   /**
      * Connect to MySQL.
      * @return void
      */
       public function connectToMySQL(){
           $this->con = mysql_connect($this->hostname,$this->username,$this->password);
           if($this->con){
               echo "
Connected sucessfully to MySQL .
";
           }
           else{
               die( "
Could not connect to MySQL" . mysql_error() . ".
");
           }
       }


 }      





class dbclose extends DBConnect{
   function closeConnection(){
      //Do something else here and at the end you can
      mysql_close();//For example
   }
}

Link to comment
Share on other sites

I am getting an error, and i am unsure what i have done wrong.

LIVE demo - http://www.designvisa.com/beta/include/dbconnect/opendb.php

 

$vconfig = new VConfig();

   //Create objects from DBObject class.
   $myObj = new DBConnect("localhost","$vconfig->user","$vconfig->dbpass","$vconfig->db");

   //Call methods of objects.
   $myObj ->connectToMySQL();

   $myObj2 = new DBData();
   $myObj2 ->selectDB();
   $myObj2 ->showMessage();

class  DBConnect{
       /////////////////////////////////////////////////
       // PRIVATE PROPERTIES  
       /////////////////////////////////////////////////
       private $hostname, $username, $password, $db_name, $con;

   /**
      * Constructor
      * @param String $hostname,$username,$password,$db_name. 
      * All information we need to provide whenever connect to db.
      */
       public function __construct($hostname,$username,$password,$db_name){
           $this->hostname = $hostname;
           $this->username = $username;
           $this->password = $password;
           $this->db_name = $db_name;
       }

   /**
      * Connect to MySQL.
      * @return void
      */
       public function connectToMySQL(){
           $this->con = mysql_connect($this->hostname,$this->username,$this->password);
           if($this->con){
               echo "
Connected sucessfully to MySQL .
";
           }
           else{
               die( "
Could not connect to MySQL" . mysql_error() . ".
");
           }
       }


 }      



class DBData extends DBConnect{

public function selectDB(){
           $result = mysql_select_db($this->db_name,$this->con);
           if($result){
               echo "
Connected sucessfully to database ' ".$this->db_name." ' .
";
           }
           else{
               die( "
Could not connect to database ' ". $this->db_name. " '  ".mysql_error() . ".
");
           }
       }
}




class DBClose extends DBConnect{
   function closeConnection(){
      //Do something else here and at the end you can
      mysql_close();//For example
   }
}

 

Can anyone help!

Link to comment
Share on other sites

I am getting an error, and i am unsure what i have done wrong.

LIVE demo - http://www.designvisa.com/beta/include/dbconnect/opendb.php

 

$vconfig = new VConfig();

   //Create objects from DBObject class.
   $myObj = new DBConnect("localhost","$vconfig->user","$vconfig->dbpass","$vconfig->db");

   //Call methods of objects.
   $myObj ->connectToMySQL();

   $myObj2 = new DBData();
   $myObj2 ->selectDB();
   $myObj2 ->showMessage();

class  DBConnect{
       /////////////////////////////////////////////////
       // PRIVATE PROPERTIES  
       /////////////////////////////////////////////////
       private $hostname, $username, $password, $db_name, $con;

   /**
      * Constructor
      * @param String $hostname,$username,$password,$db_name. 
      * All information we need to provide whenever connect to db.
      */
       public function __construct($hostname,$username,$password,$db_name){
           $this->hostname = $hostname;
           $this->username = $username;
           $this->password = $password;
           $this->db_name = $db_name;
       }

   /**
      * Connect to MySQL.
      * @return void
      */
       public function connectToMySQL(){
           $this->con = mysql_connect($this->hostname,$this->username,$this->password);
           if($this->con){
               echo "
Connected sucessfully to MySQL .
";
           }
           else{
               die( "
Could not connect to MySQL" . mysql_error() . ".
");
           }
       }


 }      



class DBData extends DBConnect{

public function selectDB(){
           $result = mysql_select_db($this->db_name,$this->con);
           if($result){
               echo "
Connected sucessfully to database ' ".$this->db_name." ' .
";
           }
           else{
               die( "
Could not connect to database ' ". $this->db_name. " '  ".mysql_error() . ".
");
           }
       }
}




class DBClose extends DBConnect{
   function closeConnection(){
      //Do something else here and at the end you can
      mysql_close();//For example
   }
}

 

Can anyone help!

 

100% sure this won't work. I will reply to you soon, cause i am working now. But goodluck.

Link to comment
Share on other sites

Hi,

 

I just help you to fix the problem. I hope it works fine on your pc. Have a nice day (~_~) !

 

<?php 
  /* BEFORE YOU RUN THIS FILE, YOU SHOULD CHANGE THE PASSING VALUES  FOR CONSTRUCTOR.
      * THEN IT WILL WORK OK.
   */
  //////////////////////////////////////////////////////////////////////////////////

   /*  Acctually This object connect to db, but haven't done anything on the 
    *    database 'mysql' yet.
    */
   $myObj = new DBConnect("localhost","root","","mysql");
   $myObj ->connectToMySQL();

   /*
       You need to pass the values to the arguments for the constructor from 
       superclass DBConnect. If not $dbData won't know how to connect to database.
   */
   $dbData = new DBData("localhost","root","","information_schema");

   /*
       You need to connect to MySQL before work on any databases.
   */
   $dbData ->connectToMySQL();

   /*
       - Because the class DBData defined only one method selectDB(); 
       - Whenever you want to work with a database, you need to connect to MySQL first.
       - In your situation, You didn't call method connectToMySQL() from superclass DBObject.
       --> That's why You cannot select any databases.(Thats why you've got the errors)
   */
   $dbData ->selectDB();

   class  DBConnect{
       /////////////////////////////////////////////////
       // PROTECTED PROPERTIES  
       /////////////////////////////////////////////////
       protected $hostname, $username, $password,$db_name, $con ;

    /**
      * Constructor
      * @param String $hostname,$username,$password,$db_name. 
      * All information we need to provide whenever connect to db.
      */
       public function __construct($hostname,$username,$password,$db_name){

           $this->hostname = $hostname;
           $this->username = $username;
           $this->password = $password;
           $this->db_name = $db_name;

       }

    /**
      * Connect to MySQL.
      * @return void
      */
       public function connectToMySQL(){
           $this->con = mysql_connect($this->hostname,$this->username,$this->password);
           if($this->con){
               echo "
Connected sucessfully to MySQL .
";
           }
           else{
               die( "
Could not connect to MySQL" . mysql_error() . ".
");
           }
       }
     }      

   /*  
    * DBData class extends DBConnect
    */
   class DBData extends DBConnect{
       /* This class doesn't define any constructors. Whenever you create a object from  
        * this class, The object will automaticaly refer to constructor of 
        * super class (DBObject class). cause DBData extends from DBConnect class 
        */ 
       public function selectDB(){
           $result = mysql_select_db($this->db_name,$this->con);
           if($result){
               echo "
Connected sucessfully to database ' ".$this->db_name." ' .
";
           }
           else{
               die( "
Could not connect to database ' ". $this->db_name. " '  ".mysql_error() . ".
");
           }
       }
   }

   /*     You don't need to create a class just for closing a connection. 
    *    This method you can build  in DBConnect or DBObject class. But anyhow this is your option
    *    Maybe you have some special reason to have this class.
    */   
   class DBClose extends DBConnect{
       function closeConnection(){
          mysql_close();
       }
   }

   //GOODLUCK

?>

 

Quyen,

Link to comment
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...
 Share

×
×
  • Create New...