Answer the question
In order to leave comments, you need to log in
Am I using the class correctly?
Guys, I created a report class. Did I correctly create the logs.php file itself , where my class is used, and are there any gross errors in the class itself?
class Logs
{
protected $db;
public $id;
public $text;
public function __construct($db){
$this->db = $db;
}
public function create($text){
$query = "INSERT INTO `logs` (`date`, `text`) VALUE (NOW(), ?)";
$stmt = $db->prepare($query);
if($stmt->execute(array($text))){
return true;
}else{
return false;
}
}
public function delete($id){
$stmt = $db->prepare("DELETE FROM `logs` WHERE `id` = ?");
if($stmt->execute(array($id))){
return true;
}else{
return false;
}
}
public function getAll($id = 0){
if(!empty($id)){
$query ="SELECT * FROM `logs` WHERE `id` = '".intval($id)."'";
}else{
$query ="SELECT * FROM `logs`";
}
$stmt = $db->query($query);
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
}
//logs.php ВОПРОС БОЛЬШЕ К ЭТОЙ ЧАСТИ КОДА
$logs = new Logs(DB:instance());
if(isset($_POST['add'], $_POST['text'])){
if($logs->create($_POST['text'])){
echo 'Запись добавлена';
}else{
echo 'Ошибка добавления';
}
}
if(isset($_GET['del_id'])){
if($logs->delete($_GET['del_id'])){
echo 'Запись удалена';
}
}
echo '<h2>Все отчеты</h2>';
echo '<ul>';
foreach($logs->getAll as $v){
echo '<li>'.$v['date'].': '.$v['text'].'</li>';
}
echo '</ul>';
Answer the question
In order to leave comments, you need to log in
A quick look:
1. Why are the public attributes id and text declared in the class if they are not used anywhere?
2. You use $db->prepare everywhere, but the local variable $db is not initialized. In this code, you must refer to a class attribute, i.e. $this->db->prepare
3. Why check this check in each method
if($stmt->execute(array($text))){
return true;
}else{
return false;
}
1) the name of the class in the plural no one does. just Log.
2) use the PSR-3 Logger Interface and don't go big.
3) design type
if($stmt->execute(array($text))){
return true;
}else{
return false;
}
can always be shortened toreturn (bool)$stmt->execute(array($text));
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question