Feedback on Notes/blog entry class...
Posted: Sat May 17, 2008 12:21 pm
I wanted to get some feedback on a notes/blog entry class I have written to display posts stored in an MySQL database. What can I improve? What would you do differently? Can I do anything more efficiently? I am still VERY new to OOP.
Thanks in advance!
Thanks in advance!
Code: Select all
class Notes {
//Declaring variables
private $connection;
private $id;
//Sets MySQLi connection
public function __construct(mysqli $connection) {
$this->connection = $connection;
}
/* Sets limits for prepared statement used in the getEntries() method. If
* limits are not manually set, then default values are used.
*/
public function setLimits($skip = 0, $numberRows = 10000) {
$this->skip = $skip;
$this->numberRows = $numberRows;
}
/* Creates a two dimensional array in which entry id numbers are stored in
* the first dimension, and then for each id number, a second array (i.e.
* the second dimension) is assigned, which contains all the field values
* for that particular entry.
*/
public function getEntries() {
$query = 'SELECT id, title, note, date, timestamp FROM notes ORDER BY id DESC LIMIT ?, ?';
$statement = $this->connection->prepare($query);
$statement->bind_param('is', $this->skip, $this->numberRows);
$statement->bind_result($id, $title, $date, $note, $timestamp);
$statement->execute();
while($statement->fetch()) {
$this->data[$id] = array(
'id' => $id,
'title' => $title,
'date' => $date,
'note' => $note,
'timestamp' => $timestamp
);
}
}
/* Creates a one dimensional array in which an entry's id number and all
* other field values are stored.
*/
public function getEntry($id) {
$query = 'SELECT id, title, date, note, timestamp FROM notes WHERE id = ?';
$statement = $this->connection->prepare($query);
$statement->bind_param('s', $id);
$statement->bind_result($id, $title, $date, $note, $timestamp);
$statement->execute();
if($statement->fetch()) {
$this->data = array(
'id' => $id,
'title' => $title,
'date' => $date,
'note' => $note,
'timestamp' => $timestamp
);
}
}
//Returns the one or two dimensional array of data
public function getData() {
return $this->data;
}
}
$mysqli = new mysqli(MYSQL_SERVER,MYSQL_SERVER_USERNAME,MYSQL_SERVER_PASSWORD);
$mysqli->select_db('example_db');
$notes = new Notes($mysqli);
$notes->setLimits(0,2);
$notes->getEntries();
$data = $notes->getData();
foreach($data as $note) {
echo $note['id'] . "<br>";
echo $note['title'] . "<br>";
echo $note['date'] . "<br>";
echo nl2br($note['note']) . "<br>";
echo $note['timestamp'] . "<br>";
}
$notes->getEntry('example_id_number');
$data = $notes->getData();
echo $note['id'] . "<br>";
echo $note['title'] . "<br>";
echo $note['date'] . "<br>";
echo nl2br($note['note']) . "<br>";
echo $note['timestamp'] . "<br>";
$mysqli->close();