I have the following database query which works fine but in another question earlier, it was brought to my attention that I'm using a global, when it's not necessary. The reason for that was that I attempted to use a protected variable but being a new-comer to OOP, was unable to make it work.
Perhaps someone could show me how it should be done?
<?
class DB {
public function __construct() {
global $dbh;
try {
$dbh = new PDO('mysql:host=localhost;dbname=main_db', 'my_user', 'my_pass');
$dbh ->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch(PDOException $e) {
echo $e->getMessage();
}
}
public function getFAQCats2Array() {
global $dbh;
try {
$q = '
SELECT
`id` AS ci,
`name` AS n
FROM
`faqcat`;
';
$s = $dbh->query($q);
// initialise an array for the results
$A = array();
while ($r = $s->fetch(PDO::FETCH_ASSOC)) {
$A[] = $r;
}
$s = null;
return $A;
}
catch(PDOException $e) {
echo "Something went wrong fetching the list of FAQ categories from the database.\n";
file_put_contents(
$_SERVER['DOCUMENT_ROOT']."/PDOErrors.txt",
"\n\n\n\n".$e->__toString(), FILE_APPEND);
}
}
public function getFAQ($i, $f) {
global $dbh;
try {
$q = '
SELECT
'.$f.'
FROM
faq
WHERE
id = ?
';
$s = $dbh->prepare($q);
$s->execute(array($i));
//$s->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$r = $s->fetch();
return $r[$f];
}
catch(PDOException $e) {
echo "Something went wrong fetching the FAQ answer from the database.\n";
file_put_contents(
$_SERVER['DOCUMENT_ROOT']."/PDOErrors.txt",
"\n\n\n\n".$e->__toString(), FILE_APPEND);
}
}
}
(There were other functions in the class using the same connection string in $dbh
, but I've removed them for simplicities sake)