- Фотогалерея на PHP + MySQL + jQuery — за час с нуля
- PHP Image Gallery – Create Photo Gallery with Database
- How to create dynamic photo gallery in PHP
- Create Image Gallery in PHP
- 1. Create MySQL Database and table
- 2. Connect PHP to MYSQL Database
- 3. Create Image Upload Form
- 4. Write Image Upload Script
- Show Image Gallery with PHP
- 1. Write Image Gallery Script
- 2. Show Image Gallery
- 3. Design Image Gallery Using CSS
- 4. Create Image Gallery Model Using javascript
- Tutorial Summary –
- Related posts:
- Photo Gallery With Album Using PHP/MYSQL
- Photo Gallery With Album in PHP/MYSQL
- Photo Gallery With Album Using PHP/MYSQL Screenshots:
Фотогалерея на PHP + MySQL + jQuery — за час с нуля
Здравствуй, уважаемый хабрачитатель!
Сразу к делу – заказчик скоро начнет писать гневные письма, а над фотогалереей ты еще даже не начинал работать! Причем нужно сделать галерею с автоматизированным созданием превьюшек, комментариями, сортировкой фото и красивыми модальными окнами:
Срочно, срочно под хабракат!
Итак, у нас впереди куча работы – проектирование БД, создание админки и пользовательской части. Разберем самый простой пример – у нас просто должна быть страница с фотогалереей, без разбивки на категории и постраничной прокрутки, все это легко добавляется потом. Категории добавляются при помощи дополнительного поля в таблице с фотками, таблицы с категориями и несколькими строками кода, а про постраничный вывод из БД и так написана куча статей, на том же Хабре.
Начнем с начала – с базы данных, MySQL. Нам нужна таблица с фотками. Нужные поля: id фото, ссылка на большое изображение, ссылка на превью, комментарий к фото и порядковая позиция фото. Вот скриншот из phpMyAdmin и sql-код:
CREATE TABLE `photos` ( `id` int(5) NOT NULL auto_increment, `comment` text NOT NULL, `big` varchar(30) NOT NULL, `small` varchar(30) NOT NULL, `ord` int(5) NOT NULL default '999', PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=cp1251 AUTO_INCREMENT=157 ;
Прошу прощения за windows-1251, я не разжигаю межнациональную рознь, не используя Юникод, но у меня проблемы с UTF на локальном сервере (да-да, с руками проблемы)).
Отлично, теперь немного о используемых файлах и структуре каталогов. Для реализации клиентских скриптов используется jQuery с плагинами jCrop для создания миниатюр и fancybox для показа красивых модальных окон и галереи. Вот дерево каталогов:
В папке js – файлы jQuery и jCrop, в папке admin файлы photos.php и photo_add.php. В первом у нас базовая форма для загрузки фото, редактирование каталога фоток и изменение порядка, вот как это выглядит:
Код не привожу, там все просто, исходники получите внизу страницы 🙂
В файле photo_add.php у нас работает jCrop для создания миниатюр, который пересылает параметры миниатюры небольшому скрипту на php.
Вот код скрипта, создающего миниатюру:
if (isset($_POST['t'])) < $targ_w = $targ_h = 100; $jpeg_quality = 95; $src = "../upload/b.jpg"; $img_r = imagecreatefromjpeg($src); $dst_r = ImageCreateTrueColor( $targ_w, $targ_h ); imagecopyresampled($dst_r,$img_r,0,0,$_POST['x'],$_POST['y'],$targ_w,$targ_h,$_POST['w'],$_POST['h']); imagejpeg($dst_r,"../upload/s.jpg",$jpeg_quality); header("Location:photos.php?ok=ok"); exit; >
Фотографии загружаются в папку upload, убедитесь, что у нее есть права на запись.
За порядок фото отвечает поле `ord` в БД, по умолчанию оно равно 999 для всех фоток. Меняя это значение, можно поставить любой порядок для фото. Также можно сделать приятный Drag’n drop интерфейс для изменения порядка фото, но тогда мы не уложимся за час 🙂
Теперь перейдем к файлу gallery.php в корне нашего проекта, он и отвечает за вывод нашей красивой галереи:
В head необходимо подключить скрипты jquery и fancybox, а также иницииорвать галерею:
А вот сам код вывода наших фоток:
Тоже все очень просто, фотки выводятся по 3 в ряд в таблице.
Все готово! Пример галереи можно увидеть здесь.
Исходники загрузить здесь.
Права на все тестовые изображения принадлежат их создателям.
PHP Image Gallery – Create Photo Gallery with Database
PHP Image Gallery: Using the source code of this tutorial, You can easily create a simple & dynamic photo gallery with a database in a PHP script.
The image gallery is the most popular feature of the web application. It is used to display a collection of dynamic images on the web page. Here you will learn it through some easy steps that are very simple to understand.
First of all, You have to store some images to the server from the admin panel. After then, you can show them in the form of a gallery by fetching from a folder & MYSQL database. So, you will get standard scripts to quickly implement it in your project.
I have created an attractive & responsive PHP photo gallery with a popup model and slider feature.
How to create dynamic photo gallery in PHP
You can create a dynamic photo/image gallery with PHP through the following steps –
Learn Also –
First of all, You have to create the following folder structure
myproject |__assets/ | |__gallery-script.js | |__style.css |__uploads/ |__database.php |__image-gallery-script.php |__image-upload-form.php |__image-upload-script.php |__show-image-gallery.php
Create Image Gallery in PHP
To create an image gallery with a database, you have to configure the following steps –
1. Create MySQL Database and table
Use the following MYSQL query to create a database with the name codingstatus
Also, Use the following MYSQL query to create a table with the name gallery
CREATE TABLE `gallery` ( `id` int(10) UNSIGNED PRIMARY KEY NOT NULL AUTO_INCREMENT, `image_name` varchar(255) DEFAULT NULL, ) ENGINE=InnoD
2. Connect PHP to MYSQL Database
Now, use the following MySQL query to connect PHP to the database.
connect_error) < die("Unable to Connect database: " . $conn->connect_error); > ?>
3. Create Image Upload Form
To create an image upload form, use the following points –
- Include image-upload-script.php
- Create an HTML form, file upload browse button & submit button with the following attributes
- method= “post” – It uploads an image with security.
- enctype= “multipart/form-data” – It allows different type of image extension.
- type=” file” – It creates a file upload browse button.
- name= “image_gallery[]” – It access multiple images in an array.
- multiple – It allows us to select more than one image at a time.
- type= “submit” – It sends image value to the server.
- name= “submit” – It accesses whole input values to submit the form.
File Name – image-upload-form.php
4. Write Image Upload Script
This script will help you to upload multiple images to the server. you have to configure the following some steps to create it –
- Include the database connection file database.php.
- Assign $conn variable to a new variable $db
- Assign your table name gallery to a variable $tableName
- Call custom function upload_image() on submit the form.
- upload_image() – This function is created to upload multiple images.
- save_image() – This function is created to save an image into the MySQL database.
File Name – image-upload-script.php
function upload_image($tableName)< $uploadTo = "uploads/"; $allowedImageType = array('jpg','png','jpeg','gif'); $imageName = array_filter($_FILES['image_gallery']['name']); $imageTempName=$_FILES["image_gallery"]["tmp_name"]; $tableName= trim($tableName); if(empty($imageName))< $error="Please Select Images.."; return $error; >else if(empty($tableName))< $error="You must declare table name"; return $error; >else< $error=$savedImageBasename=''; foreach($imageName as $index=>$file)< $imageBasename = basename($imageName[$index]); $imagePath = $uploadTo.$imageBasename; $imageType = pathinfo($imagePath, PATHINFO_EXTENSION); if(in_array($imageType, $allowedImageType))< // Upload image to server if(move_uploaded_file($imageTempName[$index],$imagePath))< // Store image into database table $savedImageBasename .= "('".$imageBasename."'),"; >else < $error = 'File Not uploaded ! try again'; >>else < $error .= $_FILES['file_name']['name'][$index].' - file extensions not allowed
'; > > save_image($savedImageBasename, $tableName); > return $error; > // File upload configuration function save_image($savedImageBasename, $tableName)< global $db; if(!empty($savedImageBasename)) < $value = trim($savedImageBasename, ','); $saveImage="INSERT INTO ".$tableName." (image_name) VALUES".$value; $exec= $db->query($saveImage); if($exec)< echo "Images are uploaded successfully"; >else< echo "Error: " . $saveImage . "
" . $db->error; > > > ?>Show Image Gallery with PHP
Now, display the image gallery using the following steps –
1. Write Image Gallery Script
This script will help you to fetch images from the database. To create it, you will have to go through the following points –
- Include database connection file database.php
- Assign $conn variable to another variable $db
- Assign your table name gallery to a new variable $tableName
- Create a custom function fetch_image($tableName) with a parameter that will accept only table Name and call it by assigning to a variable $fetchImage . This function contains a MySQL SELECT query to select all the values of images from the table.
File Name – image-gallery-script.php
query($query); if ($result->num_rows > 0) < $row= $result->fetch_all(MYSQLI_ASSOC); return $row; >else < echo "No Image is stored in the database"; >>else < echo "you must declare table name to fetch Image"; >> ?>
2. Show Image Gallery
To show the image gallery on the web page, you will have to configure the following things –
- Include image gallery script file image-gallery-script.php to fetch images from the database.
- Include stylesheet file style.css to design a photo gallery in the head section.
- Print images with foreach loop applies on $fetchImage .
- Include javascript file gallery-script.js to create a Modal & slider of the photo gallery.
File Name – show-image-gallery.php
×/ 43. Design Image Gallery Using CSS
Use the following CSS code to design the image gallery. you can also add your CSS code according to your project requirement
body < box-sizing: border-box; margin:0px; padding: 0px; overflow-x: hidden; >.row > .column < margin: .5%; >.row:after < content: ""; display: table; clear: both; >.column < float: left; width: 24%; >.modal < display: none; position: fixed; z-index: 1; padding-top: 100px; left: 0; top: 0; width: 100%; height: 100%; overflow: auto; background-color: #363333ab; >.modal-content < position: relative; background-color: #fefefe; margin: auto; padding: 0; width: 90%; max-width: 1200px; >.close < color: white; position: absolute; top: 10px; right: 25px; font-size: 35px; font-weight: bold; >.gallerySlides < display: none; >.cursor < cursor: pointer; >.prev, .next < cursor: pointer; position: absolute; top: 50%; width: auto; padding: 16px; margin-top: -50px; color: white; font-weight: bold; font-size: 20px; transition: 0.6s ease; border-radius: 0 3px 3px 0; user-select: none; -webkit-user-select: none; background: #00000066; >.next < right: 0; border-radius: 3px 0 0 3px; >.numbertext < color: #171717; font-size: 20px; padding: 8px 12px; position: absolute; top: 0; font-weight: bold; >.column img < max-height: 160px; height: 160px; object-fit: contain; padding: 5px; border: 1px solid #d9d9d9; >.caption-container < text-align: center; background-color: black; padding: 2px 16px; color: white; >img.hover-shadow < transition: 0.3s; >.hover-shadow:hover
4. Create Image Gallery Model Using javascript
You have created the following functions for creating an Image gallery model –
- openModal() – It can open the image model
- closeModal() – It can close the opened image model
- showSlides(n) – It works to slide images in the gallery
File Name – gallery-script.js
function openModal() < document.getElementById("galleryModal").style.display = "block"; >function closeModal() < document.getElementById("galleryModal").style.display = "none"; >var slideIndex = 1; showSlides(slideIndex); function plusSlides(n) < showSlides(slideIndex += n); >function currentSlide(n) < showSlides(slideIndex = n); >function showSlides(n) < var i; var slides = document.getElementsByClassName("gallerySlides"); var captionText = document.getElementById("caption"); if (n >slides.length) if (n < 1) for (i = 0; i < slides.length; i++) < slides[i].style.display = "none"; >slides[slideIndex-1].style.display = "block"; >
Tutorial Summary –
I hope you like this tutorial. Even it is useful for you. So, Don’t forget to share with friends who need it.
If you have any queries, you can ask me through the below comment box. I will also share more PHP source code. So, you should continue to visit my blog for becoming an expert in the coding field.
Related posts:
Hey there, Welcome to CodingStatus. My Name is Md Nurullah from Bihar, India. I’m a Software Engineer. I have been working in the Web Technology field for 4 years. Here, I blog about Web Development & Designing. Even I help developers to build the best Web Applications.
Photo Gallery With Album Using PHP/MYSQL
This tutorial is about creating Photo Gallery With Album Using PHP/MYSQL. Some gallery tutorials commonly for uploading and displaying only the photo. In this tutorial, we add some twist in our gallery in a very simple way. You can now create your own gallery with add album feature.
In this tutorial, we can count all the photos uploaded to that album, we can view the album also as well as the uploaded photo on it.
So first, create a database. Name it as any name you desire. In my case, I choose “itsourcecode” as the name of my database.
For the album table. Create a “gallery_albums” table then put the following attributes.
CREATE TABLE `gallery_albums` ( `album_id` int(11) NOT NULL, `album_name` text NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1;
Now, for the photos. Create a “gallery_photos” table then put the following attributes.
CREATE TABLE `gallery_photos` ( `photo_id` int(11) NOT NULL, `album_id` int(11) NOT NULL, `photo_link` text NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1;
Now let’s start our PHP files.
First, create a “connection.php” file then put the following codes.
[php]$mysqli = new mysqli(‘localhost’, ‘root’, ”, ‘itsourcecode’);
?>[/php]On the “index.php” file, put the following codes.
[php]Photo Gallery With Album in PHP/MYSQL
if (isset($_GET[‘add_album_action’])) if ($_GET[‘add_album_action’] == “successfull”) < ?>
New album created!
>
?>
$albums = $mysqli->query(“SELECT * FROM gallery_albums”);
while ($album_data = $albums->fetch_assoc()) $photos = $mysqli->query(“SELECT * FROM gallery_photos WHERE album_id = “.$album_data[‘album_id’].””);?>
# ”> (num_rows; ?>)?>
[/php]For creating an album, create a “add-album.php” file then put the following codes.
[php]include ‘connection.php’;
if (isset($_POST[‘submit_album’])) $album = $_POST[‘album_name’];
$add_album = $mysqli->query(“INSERT INTO gallery_albums (album_name) VALUES (‘$album’)”);
if ($add_album) header(“Location: index.php?add_album_action=successfull”);
> else echo $mysqli-error;
>
>
?>[/php]For viewing the upload photo on the album, create a “view-album.php” file then put the following codes.
[php]include ‘connection.php’;
if (isset($_GET[‘album_id’])) $album_id = $_GET[‘album_id’];
$get_album = $mysqli->query(“SELECT * FROM gallery_albums WHERE album_id = $album_id”);
$album_data = $get_album->fetch_assoc();
> else header(“Location: index.php”);
>
?>
$photo_count = $mysqli->query(“SELECT * FROM gallery_photos WHERE album_id = $album_id”);
?>
Home | (num_rows; ?>)if (isset($_GET[‘upload_action’])) if ($_GET[‘upload_action’] == “success”) < ?>
Photo successfully added to this album!
>
?>
$photos = $mysqli->query(“SELECT * FROM gallery_photos WHERE album_id = $album_id”);
while($photo_data = $photos->fetch_assoc()) < ?>
” width=”200px” height=”200px”/>?>
[/php]And last, for adding or uploading a photo to the album. Create a “upload-photo.php” file then put the following codes.
[php]include ‘connection.php’;
$album_id = $_GET[‘album_id’];
if ($_FILES[‘photo’][‘name’] != null) move_uploaded_file($_FILES[‘photo’][‘tmp_name’], “images/”. $_FILES[‘photo’][‘name’]);
$photo_link = “images/”. $_FILES[‘photo’][‘name’];$upload_photo = $mysqli->query(“INSERT INTO gallery_photos (album_id, photo_link) VALUES ($album_id, ‘$photo_link’)”);
if ($upload_photo) header(“Location: view-album.php?album_id=$album_id&upload_action=success”);
> else echo $mysqli->error;
>
> else header(“Location: index.php”);
>
?>[/php]Photo Gallery With Album Using PHP/MYSQL Screenshots:
IF you have questions about Photo Gallery With Album Using PHP/MYSQL feel free to ask us by commenting below or by contacting us by visiting on our contact page. THANK YOU.