I’m a beginner in OOP PHP.
I’m trying to make a class that will connect,query and fetch data
I done the below coding
class MySQL {
private $set_host;
private $set_username;
private $set_password;
private $set_database;
public function __Construct($set_host, $set_username, $set_password){
$this->host = $set_host;
$this->username = $set_username;
$this->password = $set_password;
$con= mysql_connect($this->host, $this->username, $this->password);
if(!$con){ die("Couldn't connect"); }
}
public function Database($set_database)
{
$this->database=$set_database;
mysql_select_db($this->database)or die("cannot select Dataabase");
}
public function Fetch($set_table_name){
$this->table_name=$set_table_name;
$query=mysql_query("SELECT * FROM ".$this->table_name);
$result= mysql_fetch_array($query);
}
}
$connect = new MySQL('localhost','root','');
$connect->Database('cms');
$connect->Fetch('posts');
what I’m trying to achieve is this
$connect = new MySQL('localhost','root','');
$connect->Database('cms');
$connect->Fetch('posts');
and I want to fetch the data using a format like this
echo $result[0];
but I’m not getting that logic to make this happen
please help
Thanks!
Your
Fetchfunction is only pulling one row from the database, and you aren’t returning the results…The method isn’t the best, but in order to achieve what you’re trying to do:
This will make each row a part of $result, but you’ll have to access it like this:
You would call the fetch function like this:
Or in a loop:
That said, fetching the entire result set into memory is not a great idea (some would say it’s a very bad idea.)
Edit: It also looks like you have other issues with your class… I have to run but will check back tomorrow and if others haven’t set you straight I will expand.
Edit2: Ok, going to do a once-over on your class and try to explain a few things:
I hope this helps… It should get you started at least. If you have more questions you should ask them separately.