PHP crash course: Simple Blog Platform
A basic blogging platform where users can post, edit, and delete articles. Built using PHP, HTML, jQuery, AJAX, JSON, Bootstrap, CSS, and MySQL.
Topics: php, mysql, blog, ajax, bootstrap, jquery, css
Step-by-Step Solution
1. Directory Structure
simple-blog-platform/ │ ├── config.sample.php ├── index.html ├── db/ │ └── database.sql ├── src/ │ ├── get-post.php │ └── post-handler.php ├── include/ │ ├── config.sample.php │ └── db.php ├── assets/ │ ├── css/ │ │ └── style.css │ ├── js/ │ │ └── script.js │ └── images/ ├── README.md └── .gitignore
2. Database Schema
db/database.sql:
CREATE DATABASE IF NOT EXISTS blog_db; USE blog_db; CREATE TABLE IF NOT EXISTS posts ( id INT AUTO_INCREMENT PRIMARY KEY, title VARCHAR(255) NOT NULL, content TEXT NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP );
3. Configuration File
include/config.sample.php:
<?php define('DB_HOST', 'localhost'); // Database host define('DB_NAME', 'blog_db'); // Database name define('DB_USER', 'root'); // Change if necessary define('DB_PASS', ''); // Change if necessary ?>
4. Configure the Database Connection
include/db.php:
<?php include 'config.php'; // Database configuration $dsn = 'mysql:host='.DB_HOST.';dbname='.DB_NAME; $options = [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, ]; // Create a new PDO instance try { $pdo = new PDO($dsn, DB_USER, DB_PASS, $options); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Set error mode to exception } catch (PDOException $e) { echo 'Connection failed: ' . $e->getMessage(); // Display error message if connection fails } ?>
5. HTML and PHP Structure
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Simple Blog</title> <link rel="stylesheet" href="assets/css/style.css"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> </head> <body> <div class="container"> <h1 class="mt-5">Simple Blog</h1> <div id="posts"></div> <button class="btn btn-primary mt-3" data-toggle="modal" data-target="#postModal">Add Post</button> </div> <!-- Modal for adding/editing posts --> <div class="modal fade" id="postModal" tabindex="-1" role="dialog" aria-labelledby="postModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="postModalLabel">Add Post</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body"> <form id="postForm"> <input type="hidden" id="postId"> <div class="form-group"> <label for="title">Title</label> <input type="text" class="form-control" id="title" required> </div> <div class="form-group"> <label for="content">Content</label> <textarea class="form-control" id="content" rows="3" required></textarea> </div> <button type="submit" class="btn btn-primary">Save Post</button> </form> </div> </div> </div> </div> <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/js/bootstrap.bundle.min.js"></script> <script src="assets/js/script.js"></script> </body> </html>
6. JavaScript and AJAX
assets/js/script.js
$(document).ready(function() { // Load posts when the page loads loadPosts(); // Handle form submission $('#postForm').submit(function(event) { event.preventDefault(); // Prevent default form submission var postId = $('#postId').val(); var title = $('#title').val(); var content = $('#content').val(); $.ajax({ url: 'src/post-handler.php', type: 'POST', dataType: 'json', data: { id: postId, title: title, content: content }, success: function(response) { if (response.success) { $('#postModal').modal('hide'); loadPosts(); // Reload posts after saving } else { alert('Error: ' + response.message); } } }); }); // Load posts function function loadPosts() { $.ajax({ url: 'src/get-posts.php', type: 'GET', dataType: 'json', success: function(data) { var postsHtml = ''; $.each(data.posts, function(index, post) { postsHtml += '<div class="post"><h2>' + post.title + '</h2><p>' + post.content + '</p></div>'; }); $('#posts').html(postsHtml); } }); } });
7. Backend PHP Scripts
src/get-posts.php
<?php include '../include/db.php'; header('Content-Type: application/json'); try { $stmt = $pdo->query('SELECT * FROM posts ORDER BY created_at DESC'); $posts = $stmt->fetchAll(PDO::FETCH_ASSOC); echo json_encode(['posts' => $posts]); } catch (PDOException $e) { echo json_encode(['error' => $e->getMessage()]); } ?>
src/post-handler.php
<?php include '../include/db.php'; header('Content-Type: application/json'); // Retrieve POST data $id = isset($_POST['id']) ? intval($_POST['id']) : 0; $title = $_POST['title']; $content = $_POST['content']; try { if ($id > 0) { // Update existing post $stmt = $pdo->prepare('UPDATE posts SET title = ?, content = ? WHERE id = ?'); $stmt->execute([$title, $content, $id]); } else { // Insert new post $stmt = $pdo->prepare('INSERT INTO posts (title, content) VALUES (?, ?)'); $stmt->execute([$title, $content]); } echo json_encode(['success' => true]); } catch (PDOException $e) { echo json_encode(['success' => false, 'message' => $e->getMessage()]); } ?>
6. CSS Styling
assets/css/style.css
body { font-family: Arial, sans-serif; margin: 0; padding: 0; } .container { margin-top: 20px; } .post { border: 1px solid #ddd; padding: 15px; margin-bottom: 15px; background-color: #f9f9f9; }
Documentation and Comments
- config.php: Contains database configuration and connects to MySQL using PDO.
- index.php: Main page with HTML structure, includes Bootstrap for styling, and a modal for adding/editing posts.
- assets/js/script.js: Handles AJAX requests for loading and saving posts. Uses jQuery for DOM manipulation and AJAX.
- get-posts.php: Fetches posts from the database and returns them as JSON.
- post-handler.php: Handles post creation and updating based on the presence of an ID.
This setup provides a basic blogging platform where users can add and edit posts. You can expand this by adding user authentication, post categories, comments, and more.
Connecting Links
If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks ?. Your support would mean a lot to me!
If you want more helpful content like this, feel free to follow me:
- GitHub
Source Code
The above is the detailed content of PHP crash course: Simple Blog Platform. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Common problems and solutions for PHP variable scope include: 1. The global variable cannot be accessed within the function, and it needs to be passed in using the global keyword or parameter; 2. The static variable is declared with static, and it is only initialized once and the value is maintained between multiple calls; 3. Hyperglobal variables such as $_GET and $_POST can be used directly in any scope, but you need to pay attention to safe filtering; 4. Anonymous functions need to introduce parent scope variables through the use keyword, and when modifying external variables, you need to pass a reference. Mastering these rules can help avoid errors and improve code stability.

To safely handle PHP file uploads, you need to verify the source and type, control the file name and path, set server restrictions, and process media files twice. 1. Verify the upload source to prevent CSRF through token and detect the real MIME type through finfo_file using whitelist control; 2. Rename the file to a random string and determine the extension to store it in a non-Web directory according to the detection type; 3. PHP configuration limits the upload size and temporary directory Nginx/Apache prohibits access to the upload directory; 4. The GD library resaves the pictures to clear potential malicious data.

There are three common methods for PHP comment code: 1. Use // or # to block one line of code, and it is recommended to use //; 2. Use /.../ to wrap code blocks with multiple lines, which cannot be nested but can be crossed; 3. Combination skills comments such as using /if(){}/ to control logic blocks, or to improve efficiency with editor shortcut keys, you should pay attention to closing symbols and avoid nesting when using them.

The key to writing PHP comments is to clarify the purpose and specifications. Comments should explain "why" rather than "what was done", avoiding redundancy or too simplicity. 1. Use a unified format, such as docblock (/*/) for class and method descriptions to improve readability and tool compatibility; 2. Emphasize the reasons behind the logic, such as why JS jumps need to be output manually; 3. Add an overview description before complex code, describe the process in steps, and help understand the overall idea; 4. Use TODO and FIXME rationally to mark to-do items and problems to facilitate subsequent tracking and collaboration. Good annotations can reduce communication costs and improve code maintenance efficiency.

AgeneratorinPHPisamemory-efficientwaytoiterateoverlargedatasetsbyyieldingvaluesoneatatimeinsteadofreturningthemallatonce.1.Generatorsusetheyieldkeywordtoproducevaluesondemand,reducingmemoryusage.2.Theyareusefulforhandlingbigloops,readinglargefiles,or

TolearnPHPeffectively,startbysettingupalocalserverenvironmentusingtoolslikeXAMPPandacodeeditorlikeVSCode.1)InstallXAMPPforApache,MySQL,andPHP.2)Useacodeeditorforsyntaxsupport.3)TestyoursetupwithasimplePHPfile.Next,learnPHPbasicsincludingvariables,ech

In PHP, you can use square brackets or curly braces to obtain string specific index characters, but square brackets are recommended; the index starts from 0, and the access outside the range returns a null value and cannot be assigned a value; mb_substr is required to handle multi-byte characters. For example: $str="hello";echo$str[0]; output h; and Chinese characters such as mb_substr($str,1,1) need to obtain the correct result; in actual applications, the length of the string should be checked before looping, dynamic strings need to be verified for validity, and multilingual projects recommend using multi-byte security functions uniformly.

ToinstallPHPquickly,useXAMPPonWindowsorHomebrewonmacOS.1.OnWindows,downloadandinstallXAMPP,selectcomponents,startApache,andplacefilesinhtdocs.2.Alternatively,manuallyinstallPHPfromphp.netandsetupaserverlikeApache.3.OnmacOS,installHomebrew,thenrun'bre
