1

i have problem in MYSQL select in OOP PHP. i do not know how to write it correct. my code is:

$sql = "SELECT name_mcategory 
            FROM web_main_category WHERE userid=('".$userid."')";
    $result = mysql_query($sql);
    $e=0;
    $maincat=array ();
    while($data=mysql_fetch_array($result))
    { 
        $maincat[$e]=$data['name_mcategory'];
        $e++;

    } 

how to write it in the OOP? i have tried this but it was not working.

class nweb {
var $userid;
var $mcategory;


function Getmain_category () {

$rs = mysql_query("SELECT name_mcategory 
            FROM web_main_category WHERE userid=$this->userid");
  }
$this->tab=mysql_fetch_object($rs);
}
   }

in the print page

$mcat = new nweb();
$mcat->getmain_category ();
$mcat->mcategory=$this->name_mcategory;

how to get data like a $maincat[$e]=$data['name_mcategory'];

3 Answers 3

1

If you want to use OOP, then use an OOP DB Layer like PDO:

class nweb extends PDO {

  public $userid, $mcategory;

  public function __construct($hostname, $dbname, $username, $password) {
    parent::__construct($hostname,$dbname,$username,$password);
  }

  public function getmain_category() {
     return $this->query("SELECT name_mcategory FROM web_main_category WHERE userid = {$this->userid}")->fetch();
  }
}

$mcat = new nweb('hostname', 'dbname', 'username', 'password');
var_dump($mcat->getmain_category());

Note: You add some error handing, see pdo::query.

Sign up to request clarification or add additional context in comments.

Comments

0

In OOP we usually make a separate class to handle the database operation . For example Database.php so it executes the query and return the result to Category.php or make Category inherit Database.php. If you want a better way use the PHP Activerecord.

Comments

0

check like this

 class nweb {
   var $userid;
   var $mcategory;


  function getmain_category () {

             $rs = mysql_query("SELECT name_mcategory 
                    FROM web_main_category WHERE userid = {$this->userid}");

             return mysql_fetch_object($rs);
  }

}



//print page


   $mcat = new nweb();
   $data = $mcat->getmain_category ();

   $e=0;
   $maincat=array ();
   while($data=mysql_fetch_array($result))
   { 
        $maincat[$e]=$data['name_mcategory'];
        $e++;
   } 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.