1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[SQL] Why is it working with cover, but not working with avatar variable? It works with one...

Discussão em 'Outras Linguagens' iniciado por Stack, Novembro 8, 2024 às 02:02.

  1. Stack

    Stack Membro Participativo

    Sorry to bother, here I am again. I have this error:

    var_dump is giving null at $avatar variable

    but the interesting thing, it is giving an url at url_users in table users of my database

    1-) I have these php codes, this are the parts and the codes that works (the $cover variable is working):

    class Admin extends Controller
    {

    public function __construct()
    {
    // Calling database communication models
    $this->postModel = $this->model('Post');
    $this->userModel = $this->model('User');
    $this->categoryModel = $this->model('Category');

    // add methods from model to vars
    $this->posts = $this->postModel->readPosts();
    $this->categories = $this->categoryModel->readCategories();

    $admin = $this->userModel->readAdmin();
    if(!$admin->lv == $_SESSION['user_lv']){
    session_destroy();
    Url::redirect('./');
    }

    }

    // show admin view
    public function index() {
    $this->view('admin/index');
    }


    /* check and register posts */
    public function postRegister()
    {

    // receiving form's data and filtering it
    // https://stackoverflow.com/questions/69207368/constant-filter-sanitize-string-is-deprecated
    // $form = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
    // $form = filter_input_array(INPUT_POST, FILTER_SANITIZE_FULL_SPECIAL_CHARS);
    $form = filter_input_array(INPUT_POST, FILTER_DEFAULT);
    if (isset($form)) :

    $cover = $_FILES['cover']['tmp_name'] ? $_FILES['cover'] : null;
    // var_dump($cover);

    $data = [
    'category_id' => trim($form['category_id']),
    'title' => trim($form['title']),
    'txt' => trim($form['txt']),
    'user_id' => $_SESSION['user_id'],
    'category_err',
    'title_err' => '',
    'txt_err' => '',
    'upload_err' => '',
    'categories' => $this->categories
    ];

    // null fields check
    if (in_array("", $form)) :

    if (empty($form['category_id'])) :
    $data['category_err'] = 'Select a Category';
    endif;

    if (empty($form['title'])) :
    $data['title_err'] = 'Fill the title field';
    endif;

    if (empty($form['txt'])) :
    $data['txt_err'] = 'Fill the text field';
    endif;

    else :

    if ($cover) :
    // thanks to autoload class, include is not necessary
    $upload = new Upload();
    $upload->image(
    $cover,
    Url::friendlyUrl($form['title'])
    );
    if ($upload->getResult()) :
    $cover = $upload->getResult();
    else :
    $cover = null;
    $data['upload_err'] = $upload->getError();
    endif;
    endif;

    // see last video 12:00
    $data['cover'] = $cover;

    if (!$data['upload_err']) :
    // saving posts in database
    if ($this->postModel->save($data)) :
    // echo 'Post Successfully Registered <hr>';
    Session::msg('post', 'Post Successfully Registered');
    Url::redirect('admin/list/posts');
    else :
    die("Error saving post at database");
    endif;
    endif;

    endif;
    else :
    $data = [
    'categories' => $this->categories,
    'title' => '',
    'txt' => '',

    'category_err' => '',
    'title_err' => '',
    'txt_err' => '',
    'upload_err' => ''
    ];

    endif;

    // defines form's view for posts' register
    $this->view('admin/posts/register', $data);
    }



    2-) Here is Posts Controller

    class Posts extends Controller {

    public function __construct()
    {
    // Calling database communication models
    $this->postModel = $this->model('Post');
    $this->userModel = $this->model('User');
    $this->categoryModel = $this->model('Category');
    }

    // public function index($id) {
    public function index($url_posts) {
    // calling method to read posts by Id at postModel
    // $post = $this->postModel->readPostById($id);
    $post = $this->postModel->readPostByUrl($url_posts);

    if($post == null) {
    Url::redirect('pages/error');
    }

    // calling method to read user by Id at userModel
    $author = $this->userModel->readUserById($post->user_id);
    $admin = $this->userModel->readAdmin();
    $categories = $this->categoryModel->readCategories();
    $category = $this->categoryModel->readCategoryById($post->category_id);

    // defining data view
    $data = [
    'post' => $post,
    'author' => $author,
    'categories' => $categories,
    'category' => $category,
    'admin' => $admin
    ];

    // defining view to show post
    $this->view('posts/show', $data);
    }


    3-) and here is Post Model

    class Post {

    private $db;
    private $table = 'posts';

    public function __construct()
    {
    // db connection's class instance
    $this->db = new Db();
    }

    public function readPosts() {
    // INNER JOIN association queries
    // Selects by user's Id
    $this->db->query("SELECT *,
    posts.id as postId,
    posts.url_posts as postUrl,
    posts.created_at as postRegisterDate,
    users.id as userId,
    users.created_at as userRegisterDate
    FROM {$this->table}
    INNER JOIN users ON
    posts.user_id = users.id
    ORDER BY posts.id DESC");
    return $this->db->results();
    }

    // saving post at db
    public function save($data) {

    // $data['url_posts'] = Url::friendlyUrl($data["title"]);
    $data['url_posts'] = $this->titleCheck($data['title']);


    $this->db->query("INSERT INTO {$this->table} (user_id, category_id, url_posts, cover, title, txt) VALUES :)user_id, :category_id, :url_posts, :cover, :title, :txt)");

    $this->db->bind("user_id", $data['user_id']);
    $this->db->bind("category_id", $data['category_id']);
    $this->db->bind("url_posts", $data['url_posts']);
    $this->db->bind("cover", $data['cover']);
    $this->db->bind("title", $data['title']);
    $this->db->bind("txt", $data['txt']);

    if($this->db->exec()):
    return true;
    else:
    return false;
    endif;
    }

    public function update($data) {

    // $data['url_posts'] = Url::friendlyUrl($data["title"]);
    $data['url_posts'] = $this->titleCheck($data['title'], $data['id']);

    $this->db->query("UPDATE {$this->table} SET category_id = :category_id,
    url_posts = :url_posts, title = :title, txt = :txt, updated_at = NOW() WHERE id = :id");

    $this->db->bind("id", $data['id']);
    $this->db->bind("category_id", $data['category_id']);
    $this->db->bind("url_posts", $data['url_posts']);
    $this->db->bind("title", $data['title']);
    $this->db->bind("txt", $data['txt']);


    if($this->db->exec()):
    return true;
    else:
    return false;
    endif;
    }

    public function readPostById($id){
    $this->db->query("SELECT * FROM {$this->table} WHERE id = :id");
    $this->db->bind('id', $id);

    return $this->db->result();
    }

    public function readPostByUrl($url_posts){

    $this->visitCount($url_posts);

    $this->db->query("SELECT * FROM {$this->table} WHERE url_posts = :url_posts");
    $this->db->bind('url_posts', $url_posts);

    return $this->db->result();
    }

    public function delete($id) {
    // var_dump($id);

    $this->db->query("DELETE FROM {$this->table} WHERE id = :id");

    $this->db->bind("id", $id);

    if($this->db->exec()):
    return true;
    else:
    return false;
    endif;
    }

    public function findPost($search)
    {
    $this->db->query("SELECT * FROM {$this->table} WHERE (title LIKE '%' :search '%' OR txt LIKE '%' :search '%') ORDER BY id DESC");
    $this->db->bind('search', $search);

    return $this->db->results();
    }

    public function count(){
    return $this->db->totalResults();
    }

    public function titleCheck($title, $id = null){

    $sql = (!empty($id) ? "id != {$id} AND" : "");

    $this->db->query("SELECT * FROM {$this->table} WHERE {$sql} title = :t");
    $this->db->bind('t', $title);

    if($this->db->result()) :
    // return Url::friendlyUrl($title).'-'.uniqid();
    return Url::friendlyUrl($title).'-'.date('d-m-Y-h_i-s', time());
    else:
    return Url::friendlyUrl($title);
    endif;
    }

    private function visitCount($url_posts)
    {
    $this->db->query("UPDATE {$this->table} SET visits = visits + 1, last_visit = NOW() WHERE url_posts = :u_posts");

    $this->db->bind("u_posts", $url_posts);

    if ($this->db->exec()) :
    return true;
    else :
    return false;
    endif;
    }


    4-) Ok, the real question goes here where is not working, I have Users Controller with the $avatar variable, the problem is with this line ($avatar = $_FILES['avatar']['tmp_name'] ? $_FILES['avatar'] : null;), but here goes the code:

    class Users extends Controller {

    public function __construct()
    {
    // $this is a pseudo-var, calls User Model for database communication
    $this->userModel = $this->model('User');
    }

    public function index($url_users) {

    $user = $this->userModel->readUserByUrl($url_users);

    if($user == null) {
    Url::redirect('pages/error');
    }

    // defining data view
    $data = [
    'user' => $user
    ];

    // defining view to show post
    $this->view('users/profile', $data);
    }

    // user data checking and edition by Id
    public function profile($id)
    {
    // search user at model by Id
    $user = $this->userModel->readUserById($id);


    // receiving form's data and filtering it
    // receiving form's data and filtering it
    // https://stackoverflow.com/questions/69207368/constant-filter-sanitize-string-is-deprecated
    // $form = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
    // $form = filter_input_array(INPUT_POST, FILTER_SANITIZE_FULL_SPECIAL_CHARS);
    $form = filter_input_array(INPUT_POST, FILTER_DEFAULT);

    if (isset($form)) :

    $avatar = $_FILES['avatar']['tmp_name'] ? $_FILES['avatar'] : null;

    // defining data
    $data = [
    'id' => $id,
    // 'avatar' => trim($form['avatar']),
    // 'avatar' => $avatar,
    'username' => trim($form['username']),
    'email' => trim($form['email']),
    'pass' => trim($form['pass']),
    'bio' => trim($form['bio']),
    'facebook' => trim($form['facebook']),
    'youtube' => trim($form['youtube']),
    'instagram' => trim($form['instagram']),
    'username_err' => '',
    'email_err' => '',
    'pass_err' => '',
    'upload_err' => '',
    ];

    // empty field checking
    if (empty($form['pass'])) :
    // defining password as user's password at database
    $data['pass'] = $user->pass;
    else :
    // if not empty field, encodes password
    $data['pass'] = password_hash($form['pass'], PASSWORD_DEFAULT);
    endif;

    // if empty, receives the one at db
    if (empty($form['bio'])) :
    $data['bio'] = $user->bio;
    endif;

    // if empty
    if (empty($form['username']) || empty($form['email'])) :

    if (empty($form['username'])) :
    $data['username_err'] = 'Fill the name field';
    endif;

    if (empty($form['email'])) :
    $data['email_err'] = 'Fill the e-mail field ';
    endif;

    else :

    if ($avatar) :
    // thanks to autoload class, include is not necessary
    $upload = new Upload();
    $upload->image(
    $avatar,
    Url::friendlyUrl($form['username'])
    );
    if ($upload->getResult()) :
    $avatar = $upload->getResult();
    else :
    $avatar = null;
    $avatar['upload_err'] = $upload->getError();
    endif;
    endif;

    // see last video 12:00
    $data['avatar'] = $avatar;

    // is email equal to db's
    if ($form['email'] == $user->email) :
    $this->userModel->update($data);
    Session::msg('user', 'Profile updated successfully');
    // is email already in database
    elseif (!$this->userModel->emailCheck($form['email'])) :
    $this->userModel->update($data);
    Session::msg('user', 'Profile updated successfully');
    else :
    $data['email_err'] = 'Informed e-mail already exist';
    endif;

    endif;
    else :
    // is user authorized to edit profile
    if ($user->id != $_SESSION['user_id']) :
    Session::msg('post', "You're not allowed to edit this profile", 'alert alert-danger');
    Url::redirect('posts');
    endif;

    //defining view data
    $data = [
    'id' => $user->id,
    // 'avatar' => $user->avatar,
    'username' => $user->username,
    'email' => $user->email,
    'bio' => $user->bio,
    'facebook' => $user->facebook,
    'youtube' => $user->youtube,
    'instagram' => $user->instagram,
    'username_err' => '',
    'email_err' => '',
    'pass_err' => '',
    'upload_err' => ''
    ];

    endif;

    //defining view file
    $this->view('users/profile', $data);
    }



    5-) And User Model

    class User {

    private $db;
    private $table = 'users';

    public function __construct()
    {
    $this->db = new Db();
    }

    public function emailChecking($email) {
    $this->db->query("SELECT email FROM {$this->table} WHERE email = :e");
    $this->db->bind(":e", $email);

    if($this->db->result()):
    return true;
    else:
    return false;
    endif;

    }

    public function save($data) {
    $this->db->query("INSERT INTO {$this->table}(username, email, pass) VALUES :)username, :email, :pass)");

    $this->db->bind("username", $data['username']);
    $this->db->bind("email", $data['email']);
    $this->db->bind("pass", $data['pass']);

    if($this->db->exec()):
    return true;
    else:
    return false;
    endif;
    }

    public function update($data) {

    $data['url_users'] = $this->nameCheck($data['username'], $data['id']);

    $this->db->query("UPDATE {$this->table} SET avatar = :avatar, url_users = :url_users, username = :username, email = :email, pass = :pass, bio = :bio, facebook = :facebook, youtube = :youtube, instagram = :instagram WHERE id = :id");

    $this->db->bind("id", $data['id']);
    $this->db->bind("avatar", $data['avatar']);
    $this->db->bind("url_users", $data['url_users']);
    $this->db->bind("username", $data['username']);
    $this->db->bind("email", $data['email']);
    $this->db->bind("pass", $data['pass']);
    $this->db->bind("bio", $data['bio']);
    $this->db->bind("facebook", $data['facebook']);
    $this->db->bind("youtube", $data['youtube']);
    $this->db->bind("instagram", $data['instagram']);


    if($this->db->exec()):
    return true;
    else:
    return false;
    endif;
    }


    public function loginChecking($email, $pass) {
    $this->db->query("SELECT * FROM {$this->table} WHERE email = :e");
    $this->db->bind(":e", $email);

    if($this->db->result()):
    $result = $this->db->result();
    if(password_verify($pass, $result->pass)):
    return $result;
    else:
    return false;
    endif;
    else:
    return false;
    endif;
    }

    public function readUserById($id){
    $this->db->query("SELECT * FROM {$this->table} WHERE id = :id");
    $this->db->bind('id', $id);

    return $this->db->result();
    }

    public function readUserByUrl($url_users){

    $this->db->query("SELECT * FROM {$this->table} WHERE url_users = :url_users");
    $this->db->bind('url_users', $url_users);

    return $this->db->result();
    }

    public function readAdmin(){
    $this->db->query("SELECT * FROM {$this->table} WHERE lv = 3");
    return $this->db->result();
    }

    public function nameCheck($username, $id = null){

    $sql = (!empty($id) ? "id != {$id} AND" : "");

    $this->db->query("SELECT * FROM {$this->table} WHERE {$sql} username = :usrn");
    $this->db->bind('usrn', $username);

    if($this->db->result()) :
    // return Url::friendlyUrl($title).'-'.uniqid();
    return Url::friendlyUrl($username).'-'.date('d-m-Y-h_i-s', time());
    else:
    return Url::friendlyUrl($username);
    endif;

    }


    6-) The question is, I am not seeing where it is wrong, why I get what I want with $cover, but using the same logic not getting anything at $avatar.... I really have no clue at all....

    7-) I was trying to get an Image at $avatar for users the same way I did with $cover for posts....

    But the output isn't getting anything, just null at $avatar.

    Continue reading...

Compartilhe esta Página