mysql - OOP PHP connect and select functions
Get the solution ↓↓↓Hey guys i've come across the following problem. I have a database class with a fully working connect function, I am now wanting to use this myconn variable in my other class News. I keep getting error messages whichever way i go around it. One of the messages is;
Call to a member function prepare() on a non-object in C:\Users\PC\Documents\XAMPP\htdocs\class.News.php on line 10
I am new to OOP so any help will be greatly appreciated.
class.Database
<?php
class Database{
private $db_host = 'localhost';
private $db_user = 'c3337015';
private $db_pass = 'c3337015';
private $db_name = 'iitb';
public $myconn;
public function connect(){
if(!isset($this->myconn)){
$this->myconn = mysqli_connect($this->db_host,$this->db_user,$this->db_pass,$this->db_name);
if($this->myconn){
echo "connected"; // echoing just for testing purposes
return true;
}else{
echo "failed";
return false;
}}else{
echo "already connected";
return false;
}
}
public function disconnect()
{
if(isset($this->myconn))
{
if(mysqli_close($this->myconn))
{
$this->myconn = false;
echo "connection closed";
return true;
}
else
{
echo "failed to close connection";
return false;
}
}else{
echo "no connection prescent";
}
}
}
class.News
<?php
require_once('class.Database.php');
class News extends Database{
function getNews(){
$me = new Database();
$me->connect();
// HOW DO I USE THE MYCONN VARIABLE AS DEFINED IN CLASS.DATABASE
$stmt = $this->myconn->prepare(" SELECT * FROM news ");
//the rest of the $stmt etc etc....
}
}
Answer
Solution:
If you want to use your database class in your other class, then it's other type of dependency. You class shouldn't extend database class, because it does not.
You should just include your database class as you already did and just use it.
Then you should use it like this (based on code you provided):
$me = new Database();
$me->connect();
$stmt = $me->myconn->prepare(" SELECT * FROM news ");
But you should probably read some paper on OOP before proceeding, because you do not use this paradigm correctly.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: object of class stdclass could not be converted to string
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.