Working on a particular application, I keep writing very similar queries, again and again. They're not exactly the same, but are of very similar form, and embedded in almost identical chunks of code, e.g.,
$Mysqli = new mysqli;
if ($Stmt = $Mysqli->prepare("SELECT foo
FROM tblFoo
WHERE something = ?")) {
$Stmt->bind_param('s', $this->_something);
$Stmt->execute();
if (0 != $Stmt->errno)
throw new Exception("blah, blah, blah");
$Stmt->bind_result($foo);
while ($Stmt->fetch()){
$this->_foos[] = new Foo($foo);
}
$Stmt->close();
} else {
throw new Exception("blah, blah, blah"););
}
}
and later, somewhere else ...
$Mysqli = new mysqli;
if ($Stmt = $Mysqli->prepare("SELECT bar, baz
FROM tblBar
WHERE somethingElse = ?")) {
$Stmt->bind_param('s', $this->_somethingElse);
$Stmt->execute();
if (0 != $Stmt->errno)
throw new Exception("blah, blah, blah");
$Stmt->bind_result($bar, $baz);
while ($Stmt->fetch()){
// do something else with $bar and $baz
}
$Stmt->close();
} else {
throw new Exception("blah, blah, blah"););
}
}
... and then another, and elsewhere another ... etc.
Is this a real violation of DRY? It doesn't seem to make sense to write a class for performing this kind of query (with constructor params or setters for table, column, bound variables, etc.) and then reusing it throughout my app. But at the same time, I can't shake this nagging feeling that I'm repeating myself.
Maybe it's just that there are only so many ways to write a simple query and that a certain amount of repetition like this is to be expected.
Thoughts?