Reputation: 167
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'];
Upvotes: 1
Views: 3796
Reputation: 6687
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
.
Upvotes: 1
Reputation: 2071
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++;
}
Upvotes: 0
Reputation: 175
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.
Upvotes: 0