I'm just trying to make a venture into OOP, the use of classes and functiones etc.
Here is my code so far, I don't know if database actions using classes/functions can be achieved better, I don't know if my functions work, the script simply whitepages on ?id=1 (which should say "mikey" in h1 tags.)
Like I say, I'm just starting to try to learn, so forgive me if I'm mixing procedural code in there with oop, and if there are better ways to achieve what I'm trying to do there (this is simply a test script so that I can learn)
Here is my current code:
<?php
class dB
{
function connectDB($dbhost, $dbuser, $dbpass)
{
mysql_connect("$dbhost", "$dbuser", "$dbpass") or die(mysql_error());
}
function selectDB($dbname)
{
mysql_select_db("$dbname") or die(mysql_error());
}
function fetchDB($sql)
{
if (!empty($sql)) {
$q = mysql_query($sql) or die(mysql_error());
return mysql_fetch_assoc($q) or die(mysql_error());
} else {
die("Error, empty query");
}
}
}
$dB = new dB();
$dB->connectDB("localhost", "db", "dbpass");
$dB->selectDB("db");
$id = (int)$_GET['id'];
$user = $dB->fetchDB("SELECT * FROM `users` WHERE `userid` = '$id'");
// below does the same as above. below works. above does not.
//$q = mysql_query("SELECT `username` AS 'name' FROM `users` WHERE `userid` = '$id';");
//$user = mysql_fetch_assoc($q);
echo "<h1>{$user['username']}</h1>";
}
What's meant to happen is you visit script.php?id=1 and it will fetch id 1's username, and output it in H1 tags, It isnt doing this, and I think it is my fetchDB() function which is the cause of the problem.
Any help is appreciated 😃