Home Backend Development PHP Tutorial PHP realizes the production of simple blog_php example

PHP realizes the production of simple blog_php example

Dec 05, 2016 pm 01:28 PM
php Source code

Recently, I had time to look at some PHP code. I made a simple blog with reference to the PHP100 tutorial, and I will briefly record it here.

The first is the integrated environment. WAMP is selected here: http://www.wampserver.com/en/

First create a blog table through phpMyAdmin.

Pure interface operation, the process is relatively simple. It should be noted that id is the primary key, and the auto_increnent option is set, which means that the field will automatically increment when it is empty. Other fields are more casual, just pay attention to the type and length.

Create data connection

Create the conn.php file in the ./wamp/www/blog directory.

<&#63;php

@mysql_connect("127.0.0.1:3306","root","") or die("mysql数据库连接失败");
@mysql_select_db("test")or die("db连接失败");
mysql_query("set names 'gbk'");

&#63;>

Copy after login

The default user name of mysql is root, and the password is empty. The blog created here is in the test library, so it needs to be connected to the test library.

Add blog                                             

Create the add.php file in the ./wamp/www/blog/ directory.


<a href="index.php"><B>index</B></a>
<a href="add.php"><B>add blog</B></a>
<hr>


<&#63;php
include("conn.php"); //引入连接数据库

if (!empty($_POST['sub'])) {
  $title = $_POST['title']; //获取title表单内容
  $con = $_POST['con'];   //获取contents表单内容
  $sql= "insert into blog values(null,'0','$title',now(),'$con')";
  mysql_query($sql);
  echo "insert success!";

}

&#63;>

<form action="add.php" method="post">
  title  :<br>
  <input type="text" name="title"><br><br>
  contents:<br>
  <textarea rows="5" cols="50" name="con"></textarea><br><br>
  <input type="submit" name="sub" value="submit">
  
</form>

Copy after login
This code is divided into two parts. The upper part is PHP code. The include (or require) statement will get all the text/code/tags that exist in the specified file and copy them to the file using the include statement.

Then, if it is judged that the content of name='sub' in the form is not empty, the content of the form will be obtained, and then the $sql statement will be executed. null means that the id is empty (incremented by itself), and now() means that it will be taken from the current day. , $title and $con take the content submitted by the user in the form. Finally, eche prompts for successful insertion.

The lower part is a simple HTML code, used to implement a blog form submission function.

Create the homepage of your blog​​​​​​​​​​​​​

Create the index.php file in the ./wamp/www/blog/ directory.


<a href="index.php"><B>index</B></a>
<a href="add.php"><B>add blog</B></a>
<br><br>
<form action="" method="get" style='align:"right"'>
  <input type="text" name="keys" >
  <input type="submit" name="subs" >
</form>
<hr>

<&#63;php
include("conn.php"); //引入连接数据库
  
  if (!empty($_GET['keys'])) {
    $key = $_GET['keys'];
    $w = " title like '%$key%'";

  }else{
    $w=1;
  }

  $sql ="select * from blog where $w order by id desc limit 5";
  $query = mysql_query($sql);
  
  while ($rs = mysql_fetch_array($query)) {


&#63;>
<h2>title: <a href="view.php&#63;id=<&#63;php echo $rs['id']; &#63;>"><&#63;php echo $rs['title']; &#63;></a>
  | <a href="edit.php&#63;id=<&#63;php echo $rs['id']; &#63;>">edit</a> 
  | <a href="del.php&#63;id=<&#63;php echo $rs['id']; &#63;>">delete</a> |
</h2>
<li>date: <&#63;php echo $rs['data']; &#63;></li>
<!--截取内容展示长度-->
<p>contents:<&#63;php echo iconv_substr($rs['contents'],0,30,"gbk"); &#63;>...</p> 
<hr>

<&#63;php

};

&#63;>
Copy after login
This page contains quite a few functions.

The first is a search form. Use if to determine whether the content of the search form is empty. If it is not empty, match the title of the article by entering the keyword and display the result; if it is empty, query all blog content and display each article in a loop. title, date, text. Clicking on the title will link to the detailed page of the blog. Each article provides "edit" and "delete" functions.

mysql_query() is used to execute sql statements. mysql_fetch_arry() generates an array from the returned data, so that each piece of data in the database can be operated like an array.

Then the text is displayed, and the first 30 characters of the text are extracted through the iconv_substr() function.

View the blog                                  

Create the view.php file in the ./wamp/www/blog/ directory.


<a href="index.php"><B>index</B></a>
<a href="add.php"><B>add blog</B></a>
<hr>

<&#63;php
include("conn.php"); //引入连接数据库

  if (!empty($_GET['id'])) {
    $id = $_GET['id'];
    $sql ="select * from blog where id='$id' ";  
    $query = mysql_query($sql);
    $rs = mysql_fetch_array($query);
    
    $sqlup = "update blog set hits=hits+1 where id='$id'";
    mysql_query($sqlup);
  }



&#63;>
<h2>title: <&#63;php echo $rs['title']; &#63;> </h1>
<h3>date: <&#63;php echo $rs['data']; &#63;> 
click number: <&#63;php echo $rs['hits']; &#63;></h3>
<hr>
<p>contents:<&#63;php echo $rs['contents']; &#63;></p> 

Copy after login
The implementation of blog text is relatively simple. Get the blog ID through a get request, and then query and display the title, date and text corresponding to the ID through SQL statements.

An additional small feature is to display a simple counter, every time the page is refreshed, the number of clicks is incremented by 1.

Edit blog                                                                                                                              Create the edit.php file in the ./wamp/www/blog/ directory.

<a href="index.php"><B>index</B></a>
<a href="add.php"><B>add blog</B></a>
<hr>


<&#63;php
include("conn.php"); //引入连接数据库

//获取数据库表数据
if (!empty($_GET['id'])) {
  $edit = $_GET['id'];
  $sql = "select * from blog where id='$edit'";
  $query = mysql_query($sql);
  $rs = mysql_fetch_array($query);
}

//更新数据库表数据
if (!empty($_POST['sub'])) {
  $title = $_POST['title']; //获取title表单内容
  $con = $_POST['con'];   //获取contents表单内容
  $hid = $_POST['hid']; 
  $sql= "update blog set title='$title', contents='$con' where id='$hid' ";
  mysql_query($sql);
  echo "<script>alert('update success.');location.href='index.php'</script>";

}

&#63;>

<form action="edit.php" method="post">
  <input type="hidden" name="hid" value="<&#63;php echo $rs['id'];&#63;>">
  title  :<br>
  <input type="text" name="title" value="<&#63;php echo $rs['title'];&#63;>">
  <br><br>
  contents:<br>
  <textarea rows="5" cols="50" name="con" ><&#63;php echo $rs['contents'];&#63;></textarea><br><br>
  <input type="submit" name="sub" value="submit">
  
</form>

Copy after login

The function of editing blog is relatively complicated. The operation is divided into two steps. The first step is to query the title and text of the blog and display them in the input box. The second step is to update the edited content to the database.


Delete blog


Create the del.php file in the ./wamp/www/blog/ directory.

<a href="index.php"><B>index</B></a>
<a href="add.php"><B>add blog</B></a>
<hr>


<&#63;php
  
  include("conn.php"); //引入连接数据库

  if (!empty($_GET['id'])) {
    $del = $_GET['id']; //删除blog
    $sql= "delete from blog where id='$del' ";
    mysql_query($sql);
    echo "delete success!";

  }

&#63;>

Copy after login

The last step is to implement the blog deletion function, and query and display the blog through its ID.

Because all pages are not beautified using front-end styles, they are too ugly so I won’t post pictures. The function is quite perfect. Recorded here, it is regarded as a compilation of PHP learning.

==================================================== ======

In addition, although every language has its advantages and disadvantages, I still can’t help but complain about two disadvantages of PHP.

1. Symbols are difficult to write, such as “$”, “->”, and “=>”. Although these symbols do not increase the difficulty of understanding the code syntax. But it tastes disgusting. Every time you type the "$" symbol, you have to look at the keyboard and press the shift key to find where 4 is.

2. The mixing of php and html is not too elegant in my opinion.

The above is the entire content of this article. I hope it will be helpful to everyone’s study. I also hope that everyone will support Script Home.

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles