var_dump выдает значение null в переменной $avatar
но что интересно, он выдает URL-адрес в url_users в таблице пользователей моей базы данных
1-)
У меня есть эти php-коды, это части и коды, которые работают (переменная $cover работает):
Код: Выделить всё
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 ';
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);
}
Это контроллер сообщений
Код: Выделить всё
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);
}
а вот модель публикации
Код: Выделить всё
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;
}
Хорошо, настоящий вопрос здесь, где не работает, у меня есть Users Controller с переменной $avatar, проблема в этой строке
($avatar = $_FILES['avatar']['tmp_name'] ? $_FILES['avatar'] : null;), но вот код:
Код: Выделить всё
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);
}
И модель пользователя
Код: Выделить всё
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;
}
Вопрос в том, что я не понимаю, где это не так, почему я получаю то, что хочу, с помощью $cover, но, используя ту же логику, ничего не получаю $avatar.... Я действительно понятия не имею....
7-)
Я пытался получить изображение в $avatar для пользователей таким же способом Я сделал это с помощью $cover для сообщений....
Но результат не получается что угодно, просто значение null в $avatar.
Подробнее здесь: https://stackoverflow.com/questions/791 ... -works-wit