- Как вставить HTML, CSS и JS в PHP-код?
- Первый вариант вставки элементов в PHP-код
- Второй вариант вставки элементов в PHP-код
- HTML CSS Javascript PHP MySQL To Build A Website (Simple Example)
- TABLE OF CONTENTS
- EXAMPLE DEVELOPMENT CYCLE
- STEP 1) THE PLAN – DIVIDE AND CONQUER
- STEP 2) CREATING MYSQL DATABASE TABLES
- 2A) THE SQL
- 2B) TABLE STRUCTURE
- 2C) MYSQL DATABASE NOTES & EXPLANATION
- STEP 3) SERVER-SIDE PHP SCRIPTS
- 3A) THE SCRIPT
- 3B) PHP NOTES & EXPLANATION
- STEP 4) HTML PAGE
- 4A) THE SCRIPT
- 4B) HTML NOTES & EXPLANATION
- STEP 5) THE CSS
- 5A) THE SCRIPT
- 5B) CSS NOTES & EXPLANATION
- STEP 6) THE JAVASCRIPT
- 6A) THE SCRIPT
- 6B) JAVASCRIPT NOTES & EXPLANATION
- DOWNLOAD & NOTES
- SUPPORT
- EXAMPLE CODE DOWNLOAD
- EXTRA BITS & LINKS
- SOFTWARE DEVELOPMENT LIFE CYCLE (SDLC)
- FRONT-END, BACK-END, FULL-STACK
- LINKS & REFERENCES
- INFOGRAPHIC CHEAT SHEET
- THE END
Как вставить HTML, CSS и JS в PHP-код?
Когда вы разрабатываете свой модуль, то иногда прибегаете к помощи верстки (HTML и CSS) и дополнительным скриптам.
Все это можно подключать отдельно – что-то в теле страницы, что-то в отдельных файлах. Но некоторые дополнения лучше вставлять непосредственно в сам PHP-файл.
Сегодня я покажу два варианта, как можно вставить HTML, CSS или JavaScript в код PHP.
Первый вариант вставки элементов в PHP-код
Я думаю, что если вы хоть немного знакомы с PHP, то знаете, что такое «echo» (тег, с помощью которого вы можете вывести сообщение на экран).
Вот с помощью него и можно вывести один из перечисленных ранее кодов. Пример:
"; echo $content; ?>
На что здесь стоит обратить внимание? Кавычки. Если вы используете внешние кавычки в виде » «, то внутренние кавычки элементов должны быть ‘ ‘ и наоборот, иначе вы получите ошибку. Если вы принципиально хотите использовать одинаковые и внешние, и внутренние кавычки, то во внутренних ставьте знак экранизации:
"; echo $content; ?>
В этом случае все будет работать корректно.
Второй вариант вставки элементов в PHP-код
Этот вариант мне нравится куда больше, чем первый. Здесь мы будем также использовать «echo», как и в предыдущем варианте, но добавим еще элемент «HTML»:
Сюда вы можете вставлять любой элемент, будь то HTML-код или же JavaScript. Кавычки здесь не играют роли (можете вставить любые), а по желанию можно внедрить переменные для вывода:
"; echo HTML; ?>
Весьма удобный способ для реализации ваших идей.
HTML CSS Javascript PHP MySQL To Build A Website (Simple Example)
Welcome to a beginner’s tutorial and simple example of how to use HTML, CSS, Javascript, PHP, and MySQL together to build a website. Just started with web development, and wondering how we can “put” all the different technologies together?
Various technologies and languages work together to create a website, each of them handling a different aspect.
- HTML deals with the structure and layout of web pages.
- CSS to handle the visuals and cosmetics.
- Javascript to add dynamic elements to the webpage.
- MySQL database to store data permanently.
- PHP to do server-side processing and transactions.
Yep, some of you guys may already know that. So let us walk through the development of a simple product page in this guide – Read on!
TABLE OF CONTENTS
EXAMPLE DEVELOPMENT CYCLE
All right, let us now get started with the development of the products page itself.
STEP 1) THE PLAN – DIVIDE AND CONQUER
- Goal & Overview: As Captain Obvious as this may be, we need to create a page to display products from the database.
- Server-Side Database (MySQL): To keep things simple, the database will only capture the product name and description.
- Server-Side PHP: Create a script that gets product information from the database.
- Client-Side HTML & CSS: Use the PHP script to create an HTML page to show the products, CSS for the styling.
- Client-Side Javascript: Finally, use Javascript to add dynamic elements to the HTML page. For example, what happens when the user clicks on a product.
STEP 2) CREATING MYSQL DATABASE TABLES
2A) THE SQL
-- (A) PRODUCTS TABLE CREATE TABLE `products` ( `product_id` bigint(20) NOT NULL, `product_name` varchar(128) NOT NULL, `product_description` text ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; ALTER TABLE `products` ADD PRIMARY KEY (`product_id`), ADD KEY `product_name` (`product_name`); ALTER TABLE `products` MODIFY `product_id` bigint(20) NOT NULL AUTO_INCREMENT; -- (B) DUMMY PRODUCTS INSERT INTO `products` (`product_id`, `product_name`, `product_description`) VALUES (1, 'Vulture Of Fortune', 'A sweated bump consents across the here separator.'), (2, 'Guardian Without Duty', 'Does a table migrate inside an excessive paranoid?'), (3, 'Enemies Without Hope', 'A cured parameter fears behind the phenomenon.'), (4, 'Lords Of The Void', 'The diary scores around the generalized lie.'), (5, 'Doctors And Aliens', 'The diary scores around the generalized lie.'), (6, 'Blacksmiths And Criminals', 'A considerable snail works into a purchase.');
2B) TABLE STRUCTURE
2C) MYSQL DATABASE NOTES & EXPLANATION
Personally, I will always start with the database, simply because it serves as the foundation of almost every project. It is also important to get the required fields correct right from the start, or changing the database structure later can be a very painful process.
STEP 3) SERVER-SIDE PHP SCRIPTS
3A) THE SCRIPT
PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_NAMED ]); // (C) GET PRODUCTS $stmt = $pdo->prepare("SELECT * FROM `products`"); $stmt->execute(); $products = $stmt->fetchAll();
3B) PHP NOTES & EXPLANATION
PHP is the next piece of the foundation, and the above is an oversimplified example of how we can use PHP to fetch data from the database… But this is actually kind of bad. In actual projects, we would have created a proper class library, object-oriented style. For example:
class Products < function get ($id) < // SELECT * FROM `products` WHERE `id`= $ID >function add ($name, $desc) < // INSERT INTO `products` (. FIELDS . ) >function delete ($id) < // DELETE FROM `products` WHERE `id` = $ID >>
STEP 4) HTML PAGE
4A) THE SCRIPT
?> 4B) HTML NOTES & EXPLANATION
So what is happening here!? Why is the file extension PHP instead of HTML? That’s right – We are using PHP alongside HTML here. No need to be confused. Remember the script we wrote earlier to fetch product data from the database? We are simply using it on this page to generate the product’s HTML, that’s all.
STEP 5) THE CSS
5A) THE SCRIPT
/* (A) WHOLE PAGE */ * < font-family: Arial, Helvetica, sans-serif; box-sizing: border-box; >body < max-width: 600px; padding: 10px; margin: 0 auto; background: #f2f2f2; >/* (B) BOOKS */ #books < display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); grid-gap: 10px; >.bookWrap < border: 1px solid #dbdbdb; background: #fff; >.bookImg < display: block; width: 100%; >.bookTitle < font-weight: 700; font-size: 16px; color: #333; >.bookDesc
5B) CSS NOTES & EXPLANATION
Nothing much here actually. CSS is the part that deals with cosmetics and styles in HTML.
STEP 6) THE JAVASCRIPT
6A) THE SCRIPT
window.addEventListener("load", () => < // (A) GET ALL BOOKS var books = document.querySelectorAll(".bookWrap"); // (B) ATTACH ONCLICK TO ALL BOOKS for (let book of books) < book.onclick = () =>< // (B1) GET SELECTED BOOK ID, NAME, DESCRIPTION var name = book.querySelector(".bookTitle").innerHTML, desc = book.querySelector(".bookDesc").innerHTML; // (B2) SHOW IN DIALOG BOX alert(`You have selected - ID: $, TITLE: $ DESC: $`); >; > >);
6B) JAVASCRIPT NOTES & EXPLANATION
This is yet another overly simplified example. On a “normal” products page, Javascript would have been used to send an “add to cart” process to the server when a product is selected. Also, you can pretty much already guess what Javascript can do – Remove from the cart, checkout, submit forms, form checks, load more content from the server, change themes, etc… Pretty much all kinds of processing that are dynamic.
DOWNLOAD & NOTES
Here is the download link to the example code, so you don’t have to copy-paste everything.
SUPPORT
600+ free tutorials & projects on Code Boxx and still growing. I insist on not turning Code Boxx into a «paid scripts and courses» business, so every little bit of support helps.
EXAMPLE CODE DOWNLOAD
Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
EXTRA BITS & LINKS
That’s it for all the code, and here are a few small extras that may be useful.
SOFTWARE DEVELOPMENT LIFE CYCLE (SDLC)
- Requirement Analysis – What is required? What does the client need?
- Planning – Divide-and-conquer. What needs to be done?
- Design – The database structure, software architecture, and page design.
- Development – Actual coding.
- Testing & Deployment – Test the code, and put it live on the Internet.
Some people may have different steps for the SDLC, but that is the general process. Also, take note that SDLC does not stop after just one cycle – We may review our projects later, and decide that things need to change. The whole SDLC cycle starts again, and it never really ends.
FRONT-END, BACK-END, FULL-STACK
- Project Manager (Full-Stack) – The boss. He/she/it deals with the wide overview, processes, structure of the entire system, and even support for other platforms such as mobile apps.
- Lead/Senior Web Developers (Full-Stack) – Does everything. HTML, CSS, Javascript, PHP, MySQL, and whatever else. AKA Superman.
- Junior Web Developers (Front End) – Creates the webpages. HTML, CSS, Javascript.
- Junior Web Developers (Back End) – Does PHP, MySQL. More on the administration panel and server-side libraries instead.
So yeah, it is only further up the ladder that we need to really deal with “everything and beyond”.
LINKS & REFERENCES
INFOGRAPHIC CHEAT SHEET
THE END
Thank you for reading, and we have come to the end of this guide. I hope that it has helped you to better understand – HTML, CSS, Javascript, PHP, MySQL, they are all different components, but they all work together to create a single website or system.
It may be overwhelming at first to deal with many things at once, so take it step-by-step, and the rest will be just like learning how to cycle. Once you catch the gist and flow, it will be much easier. If you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!