Can this sentence be called to extract stmt?
I'm new to PHP OOP and I have a question here. Can the sample sentence be named as follows?
$this->stmt->fetch()
?
What I am trying to do is define the $ stmt variable in my class and use it in different methods, for example:
class Display {
private $connection;
private $stmt;
public function __construct ($connection) {
$this->connection = $connection;
}
public function selectUsersValues() {
$query = "SELECT name, surname, employment_date FROM employee";
$this->stmt = $this->connection->dbh->prepare($query);
$this->stmt->execute();
}
public function displayUsersValues() {
while ($employee = $this->stmt->fetch()){
echo "<tr>";
echo "<td>".$employee['name']."</td>";
echo "<td>".$employee['surname']."</td>";
echo "<td>".$employee['employment_date']."</td>";
}
}
}
Basically in one method I just want to select the values ββand in another method I want to get all the results. Is it okay to do this, or do I only need to do this in a method selectUserValues
?
source to share
I'm new to PHP OOP and I have a question here. Can I call select an offer like this? $ This-> stmt-> fetch ()?
Yes it is possible.
Is it okay to do this, or should I just do it in the selectUserValues ββmethod?
No, this is not very good, because your client code can only use the method displayUsersValues
. This method has a temporary association with a method selectUsersValues
that is not explicit in your code. Therefore, you should force
users of your code (maybe even you, after a few weeks) use both of them. You can do this refactoring:
class Display {
private $connection;
private $stmt;
public function __construct ($connection) {
$this->connection = $connection;
}
public function selectAndDisplayUsersValues() {
$query = "SELECT name, surname, employment_date FROM employee";
$this->stmt = $this->connection->dbh->prepare($query);
$this->stmt->execute();
$this->displayUsersValues();
}
private function displayUsersValues() {
while ($employee = $this->stmt->fetch()){
echo "<tr>";
echo "<td>".$employee['name']."</td>";
echo "<td>".$employee['surname']."</td>";
echo "<td>".$employee['employment_date']."</td>";
echo "</tr>";
}
}
}
Note : your code is missingecho "</tr>";
source to share