Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Module6 task1 #10

Open
wants to merge 15 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
568cb61
Добавила функцию для выделения лотов, до которых осталось час и меньше
MariOlya May 22, 2022
562b52f
Добавила структуру базы данных
MariOlya May 22, 2022
10881cc
Внесла корректировки, добавила индекс
MariOlya May 23, 2022
2f7b60a
Добавила данные в базу данных
MariOlya May 25, 2022
95dc94c
Написала запросы на модификацию таблиц в базе данных
MariOlya May 25, 2022
6aa5cc5
Внесла данные для подключения в БД
MariOlya May 25, 2022
0fb2270
Установила соединение с БД
MariOlya May 25, 2022
957e427
Изменила структуру файлов в папке
MariOlya May 25, 2022
8a463ab
Подготовила получение и подключение лотов из БД (черновик)
MariOlya May 25, 2022
ce0b76c
Доработала запрос на показ открытых лотов
MariOlya May 26, 2022
e32e70f
Добавила вывод категорий из БД, подключила
MariOlya May 26, 2022
4b88ace
Сделала, чтобы лоту добавлялось количество ставок и максимальная ставка
MariOlya May 26, 2022
67fa459
Добавила новый сценарий, запрос к БД на получение конкретного лота
MariOlya May 26, 2022
6a56754
Оживила html, добавила функцию подсчета минимальной ставки
MariOlya May 26, 2022
ff561e3
Добавила вывод ошибки 404 при неправильном параметре itemId
MariOlya May 27, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,6 @@ Thumbs.db
vendor
uploads/*
!uploads/.gitkeep
tools/info.php
tools/adminer.php
config/db.php
8 changes: 8 additions & 0 deletions config/db.php.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?php

$db = [
'host' => 'localhost',
'user' => '',
'password' => '',
'database' => 'yeticave'
];
49 changes: 49 additions & 0 deletions functions/changers.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
<?php

/**
* Translate price to a beautiful view and add the mark rub
*
* @param array $item Array of concrete item which contains price
*
* @return string Update price
*/
function changeFormatPrice(array $item)
{
$showPrice = $item['first_price'];
if (!empty($item['price'])) {
$showPrice = $item['price'];
}
return number_format(ceil($showPrice), 0, '', ' ') . ' ₽';
}

/**
* Count how much time exist before expiry date of this item
*
* @param array $item Array of concrete item which contains this date
*
* @return int how much time exist
*/
function countLeftTime(array $item)
{
$diffToday = strtotime($item['expiry_date']) - time();
$leftHours = floor($diffToday / 3600);
$leftMinutes = floor(($diffToday - $leftHours * 3600) / 60);
return $leftHours . ':' . $leftMinutes;
}

/**
* Count min bet for current item
*
* @param array $item array of current item
*
* @return int min bet for current item
*/
function countMinBet(array $item)
{
$currentPrice = $item['first_price'];
if (!empty($item['price'])) {
$currentPrice = $item['price'];
}
$minBet = $currentPrice + $item['step_bet'];
return number_format(ceil($minBet), 0, '', ' ') . ' ₽';
}
File renamed without changes.
49 changes: 49 additions & 0 deletions functions/statings.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
<?php

/**
* Show so close expiry date from current moment
*
* @param array $item Array of concrete item which contains this date
*
* @return bool true when there is 1 hour left before the expiry date
* and false when there is more than 1 hour left before
*/
function isExpired($item)
{
if ((strtotime($item['expiry_date']) - strtotime(date('Y-m-d'))) <= 3600) {
return true;
}
return false;
}

/**
* Show exist the result of mysqli_query or we have a mistake
*
* @param mysqli $result response from our database to our request
*
* @return array from DB
*/
function isExistResult($result)
{
if (!$result) {
exit('Ошибка запроса');
}
return mysqli_fetch_all($result, MYSQLI_ASSOC);
}

/**
* Show error if $itemId is empty or doesn't exist in the item table
*
* @param array $selectedItem the item which is selected by request ID,
* if $itemId is not exist $selectedItem will be null
*
* @return string|null about error with code 404
*/
function showErrorItemId($selectedItem)
{
if (!$selectedItem) {
http_response_code(404);
return 'Ошибка 404. Страница, которую Вы ищете, не может быть найдена';
}
return null;
}
60 changes: 60 additions & 0 deletions functions/toMySQL.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
<?php

/**
* Take the newest and opened items
*
* @param mysqli $connect DB with an items table
*
* @return array of new and opened items
*/
function newItems(mysqli $connect)
{
$takeNewItems = "SELECT i.id, i.name, first_price, image, DATE_FORMAT(expiry_date, '%d.%m.%Y') "
. "as expiry_date, c.name as category, MAX(price) as price, COUNT(price) as amount_bets "
. "FROM items i "
. "LEFT JOIN bets b ON b.item_id = i.id "
. "JOIN categories c ON i.category_id = c.id "
. "WHERE expiry_date > CURRENT_TIMESTAMP "
. "GROUP BY i.id "
. "ORDER BY expiry_date DESC";
$newItems = mysqli_query($connect, $takeNewItems);
return isExistResult($newItems);
}

/**
* Take the current categories
*
* @param mysqli $connect DB with a categories table
*
* @return array of current categories
*/
function currentCategories(mysqli $connect)
{
$takeCurrentCategories = "SELECT * FROM categories";
$currentCategories = mysqli_query($connect, $takeCurrentCategories);
return isExistResult($currentCategories);
}

/**
* Take a selected item by user to look at details
*
* @param mysqli $connect DB with an items table
* @param int $itemId ID of selected item
*
* @return array of selected item
*/
function selectedItem(mysqli $connect, $itemId)
{
if (!empty($itemId)) {
$takeSelectedItem = "SELECT i.id, i.name, first_price, image, DATE_FORMAT(expiry_date, '%d.%m.%Y') "
. "as expiry_date, c.name as category, MAX(price) as price, step_bet, description "
. "FROM items i "
. "LEFT JOIN bets b ON b.item_id = i.id "
. "JOIN categories c ON i.category_id = c.id "
. "WHERE i.id = $itemId "
. "GROUP BY i.id ";
$selectedItem = mysqli_query($connect, $takeSelectedItem);
return isExistResult($selectedItem);
}
return null;
}
71 changes: 9 additions & 62 deletions index.php
Original file line number Diff line number Diff line change
@@ -1,70 +1,19 @@
<?php

require_once 'myfunction.php';
require_once 'helpers.php';
require_once 'functions/changers.php';
require_once 'functions/helpers.php';
require_once 'functions/statings.php';
require_once 'functions/toMySQL.php';
require_once 'init.php';

$is_auth = rand(0, 1);
$user_name = 'Olga'; // укажите здесь ваше имя
$categories = [
'boards' =>'Доски и лыжи',
'attachment' => 'Крепления',
'boots' => 'Ботинки',
'clothing' => 'Одежда',
'tools' => 'Инструменты',
'other' => 'Разное'
];

$items = [
[
'name' => '2014 Rossignol District Snowboard',
'category' => $categories['boards'],
'price' => 10999,
'url_image' => 'img/lot-1.jpg',
'expiry_date' => '2022-05-22'
],
[
'name' => 'DC Ply Mens 2016/2017 Snowboard',
'category' => $categories['boards'],
'price' => 159999,
'url_image' => 'img/lot-2.jpg',
'expiry_date' => '2022-05-23'
],
[
'name' => 'Крепления Union Contact Pro 2015 года размер L/XL',
'category' => $categories['attachment'],
'price' => 8000,
'url_image' => 'img/lot-3.jpg',
'expiry_date' => '2022-05-24'
],
[
'name' => 'Ботинки для сноуборда DC Mutiny Charocal',
'category' => $categories['boots'],
'price' => 10999,
'url_image' => 'img/lot-4.jpg',
'expiry_date' => '2022-05-25'
],
[
'name' => 'Куртка для сноуборда DC Mutiny Charocal',
'category' => $categories['clothing'],
'price' => 7500,
'url_image' => 'img/lot-5.jpg',
'expiry_date' => '2022-05-26'
],
[
'name' => 'Маска Oakley Canopy',
'category' => $categories['other'],
'price' => 5400,
'url_image' => 'img/lot-6.jpg',
'expiry_date' => '2022-05-27'
]
];
$currentCategories = currentCategories($connect);
$newItems = newItems($connect);

$page_content = include_template(
'main.php',
[
'categories' => $categories,
'items' => $items
'categories' => $currentCategories,
'items' => $newItems
]
);

Expand All @@ -75,10 +24,8 @@
'is_auth' => $is_auth,
'user_name' => $user_name,
'content' => $page_content,
'categories' => $categories
'categories' => $currentCategories
]
);

print ($layout_content);

?>
12 changes: 12 additions & 0 deletions init.php
Original file line number Diff line number Diff line change
@@ -1,3 +1,15 @@
<?php

require_once 'config/db.php';
date_default_timezone_set('Europe/Moscow');
$is_auth = rand(0, 1);
$user_name = 'Olga';

$connect = mysqli_connect($db['host'], $db['user'], $db['password'], $db['database']);
mysqli_set_charset($connect, 'utf8');

if (!$connect) {
$dbError = mysqli_connect_error();
$page_content = 'Ошибка подключения: ' . $dbError;
};

37 changes: 37 additions & 0 deletions lot.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<?php

require_once 'functions/changers.php';
require_once 'functions/helpers.php';
require_once 'functions/statings.php';
require_once 'functions/toMySQL.php';
require_once 'init.php';

$itemId = filter_input(INPUT_GET, 'itemId', FILTER_SANITIZE_NUMBER_INT);
$selectedItem = selectedItem($connect, $itemId);
$currentCategories = currentCategories($connect);

$page_content = showErrorItemId($selectedItem);
$title = showErrorItemId($selectedItem);
if (empty($page_content)) {
$title = $selectedItem[0]['name'];
$page_content = include_template(
'lot.php',
[
'categories' => $currentCategories,
'item' => $selectedItem[0]
]
);
}

$layout_content = include_template(
'layout.php',
[
'title' => $title,
'is_auth' => $is_auth,
'user_name' => $user_name,
'content' => $page_content,
'categories' => $currentCategories
]
);

print ($layout_content);
28 changes: 0 additions & 28 deletions myfunction.php

This file was deleted.

Loading