Hello
So I am trying to use PDO to connect to my mysql database (which I can do and results return as expected), but now I want to move these lines of code into a class so I can just pass sql to the class and have the results returned to me (preferrably as an object).
Here is the code I would like to move into a class:
$host = "localhost";
$db = "mydb";
$user = "root";
$pass = "pass";
$conn = new PDO("mysql:host=$host;dbname=$db",$user,$pass);
$sql = "SELECT * FROM users";
$q = $conn->query($sql) or die("failed!");
while($r = $q->fetch(PDO::FETCH_ASSOC)){
echo $r['title'];
}
I can pretty much figure out most of it except how to make the connection, I think:
Here's my attempt, but it's not working
class dbh {
private $host = "localhost";
private $db = "***";
private $user = "root";
private $pass = "***";
public function connect() {
$conn = new PDO("mysql:host=$this->host;
dbname=$this->db",$this->user,$this->pass);
$sql = "SELECT * FROM users";
$q = $conn->query($sql) or die("failed!");
while($r = $q->fetch(PDO::FETCH_ASSOC)){
return $r['title'];
}
}
}
$go = new dbh;
echo $go->connect();
The error I get from the above code is:
Notice: Undefined index: title in /Users/kevinalthaus/Sites/grsalefinder.com/index.php on line 45
Line 45 is the end (}) of the connect() function
Of course once I get the 'hard coded' sql code working, I will make it so the sql can be passed. I also would like this to be return as an object rather than an array, but don't know the function to do so. I thought it would be FETCH_OBJ but no such luck.
Thanks