This is the first time I’ll be making a PHP application that will have many users accessing it so where as before I didn’t have to worry about loading speeds, I do now.
These are the ways I have thought of doing it but they all seem to be a bit “hack-ish” and I’m sure there is a better way.
For the index page I could have this:
<h1><?php $job->getTitle($id); ?></h1>
<p><?php $job->getDescription($id); ?></p>
<p><?php $job->getSomethingElse($id); ?></p>
And the class as:
function getTitle($id) {
$query = "SELECT title FROM table WHERE id = $id";
$result = $db->query($query);
$row = $result->fetch_array(MYSQLI_ASSOC);
echo $row['title'];
}
function getDescription($id) {
$query = "SELECT description FROM table WHERE id = $id";
$result = $db->query($query);
$row = $result->fetch_array(MYSQLI_ASSOC);
echo $row['description'];
}
etc…
Or I could have one function, call all the results to an array. Store them as a String and explode them as I need them.
My other idea was similar to above, except I do everything in the class and echo the html.
What is the best way in terms of speed to output what I want?
Jee, have You ever listened about the MVC (Model-View-Controller) design pattern?
Though I do not want You to rewrite whole Your app, You still can get used to using of Models… By this (in very simple way) way You create a
class Modelthat has a__construct($id)method that queries the DB to load all the necessary data and store them within a private/publi/protected (whatever makes You feel good) properties.Then You call these
getXYZ()methods on that model that only returns it’s property values…Like this:
class Article {
private $title;
private $description;
private $somethingElse;
That’s it… Just one query to retrieve all the data…
In a case You want to also edit this model You can create also a
setXYZ($value)methods that will set$this->XYZ = $value;and asave()method that will update this very concrete row in the database…These methods (get and set) are called getters and setters…