OO way of accessing mysql DB??
Posted: Tue Mar 18, 2008 7:12 am
I was wondering what is the best and easiest way of accessing a mysql database? Possibly and object oriented approach? I am not really familiar with classes. Post your methods! Heres how I currently am accessing my db;
This is just one example (simplified for your viewing pleasure, of course) of a function I use with the db connect function above. Most of the functions are similar to the one below, with some minor changes to the loop for the rows. Thats why I am thinking an OO approach might be easier.
Code: Select all
function db_connect() {
// Create new database connection -host, -username, -password, -database name
@ $conn = new mysqli ('host', 'username', 'password', 'db');
if (mysqli_connect_errno()) {
echo "<p>Error: Could not connect to the database. Try again later.</p>";
exit;
}
return $conn;
}
Code: Select all
function entries($tag, $page, $postNumber) {
//Database Query
$conn = db_connect();
$query = "SELECT * FROM entries, users WHERE entries.userId = users.userId ORDER BY timestamp DESC LIMIT $from, $postNumber";
$result = $conn->query($query);
//Display Entries
if ($result->num_rows > 0) {
while ($row = $result->fetch_object()) {
echo "Posted By ".$row->name;
}
}
//If there are no entries in the database (prevent infinate loop)
else if (!($result->num_rows > 0) && ($page == 1)) {
echo "<dt>We're sorry...</dt>";
echo "<dd>There are no entries in the database yet... Please check again later.</dd>";
}
//If that page does not exist
else {
entries($tag, 1, $postNumber);
}
//Close Database
$conn->close();
}