@Chesterfield25

Как правильно сделать проверку на пустоту?

Подскажите как правильно организовать проверку на пустоту так как в данной ситуации пост запрос отправляется даже пустой?

public function create(){
        //create query
        $query = 'INSERT INTO ' . $this->table . ' SET title = :title, body = :body, author = :author, category_id = :category_id';
        //prepare statment
        $stmt = $this->conn->prepare($query);
        //clean data
        $this->title = htmlspecialchars(strip_tags($this->title));
        $this->body = htmlspecialchars(strip_tags($this->body));
        $this->author = htmlspecialchars(strip_tags($this->author));
        $this->category_id = htmlspecialchars(strip_tags($this->category_id));

        //binding of paramters
        $stmt->bindParam(':title', $this->title);
        $stmt->bindParam(':body', $this->body);
        $stmt->bindParam(':author', $this->author);
        $stmt->bindParam(':category_id', $this->category_id);

        //execute the query
        if($stmt->execute()){
            return true;
        }

        //print error if something goes wrong
        printf("Error %s. \n", $stmt->error);
        return false;
    
    }


create.php

<?php

//headers
header('Access-Control-Allow-Orign: *');
header('Content-Type: application/json');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Access-Control-Allow-Headers,Content-Type,Access-Control-Allow-Methods, Authorization, X-Requested-With');

//initializing our api
include_once('../core/initialize.php');

//instantiate post

$post = new Post($db);

//get raw posted date
$data = json_decode(file_get_contents("php://input"));

$post->title = $data->title;
$post->body = $data->body;
$post->author = $data->author;
$post->category_id = $data->category_id;

//create post
if($post->create()){
    echo json_encode(
        array('message' => 'Post created.')
    );
}else{
    echo json_encode(
        array('message' => 'Post not created.')
    );
}

?>
  • Вопрос задан
  • 147 просмотров
Пригласить эксперта
Ответы на вопрос 1
nokimaro
@nokimaro
Меня невозможно остановить, если я смогу начать.
public function create(){ 
    //clean data
    // ...
    
   if(strlen($this->body) === 0) {
        return false;
    }

    //binding of paramters
    //...
}
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы