Okay, let's say I two files and a MySQL table called Users and a table called Select.
- index.php
- fucntions.php
Users
ID NAME L_NAME POINTS 0 Jill Jackson 10 1 Jack Wills 90 2 John Doe 30
Select
ID OPTION 0 Points 1 Name 2 LastName
index.php contains a simple table and select like so.
<?php include 'output.php'; ?>
<h3>Sort by: </h3>
<select>
<?php getSelect(); ?>
</select>
<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Points</th>
</tr>
<tr>
<?php outputData(); ?>
</tr>
</table>
My fucntions.php file has the following code:
function outputData() {
try {
$handler = new PDO("mysql:host=$host;dbname=$db", "$user", "$pass");
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e)
{
echo $e->getMessage();
echo 'Sorry, an error has occurred.';
die();
}
$query = $handler->query('SELECT * FROM `Users`');
while($r = $query->fetch(PDO::FETCH_OBJ)) {
echo
'
<td>
<input type="text" value="'.$r->Name.'" >
</td>
<td>
<input type="text" value="'.$r->l_name.'">
</td>
<td>
<input type="text" value="'.$r->points.'">
</td>
';
}
}
function getSelect() {
try {
$handler = new PDO("mysql:host=$host;dbname=$db", "$user", "$pass");
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e)
{
echo $e->getMessage();
echo 'Sorry, an error has occurred.';
die();
}
$query = $handler->query('SELECT * FROM `Select`');
while($r = $query->fetch(PDO::FETCH_OBJ)) {
echo
'
<li>'.$r->option.'</li>
';
}
}
I would be using this code to output data onto multiple different pages. This is just a very basic example... I have multiple different functions for outputting and inserting data from tables. My question is, would using classes be a better option than just writing bare functions like I have here and including it on every page I need?
What are the benefits of using a class vs what I'm currently doing?
I have looked at various tutorials of how to construct classes but I've never actually found the real need as to what the benefit is when compared to what I'm doing currently...
Could someone elaborate?