PHP imitation blog park personal blog (2) database addition, modification and deletion_PHP tutorial

WBOY
Release: 2016-07-21 15:00:33
Original
1153 people have browsed it

Without further ado, there is a core concept in the previous article which is give action do something!

In this article I will use code to explain what this concept means. First look at my post.class.php. This File is our data layer processing class.

Let me briefly introduce this model class. It inherits a database base class to perform common operations such as crud. Each time it is initialized, a database object $db will be initialized. We use this object to operate our data.
There are two important methods for data operations: storePostFormValues() and storeDiaryFormValues(). These two methods are the beginning of the data flow.
There are two other interesting methods, addChildNumber( ) and reduceChildNumber( ), which are responsible for a black-box operation when inserting or deleting documents. Because my document can be classified into multiple categories, one issue I need to consider when operating the document is that there is a field in the category table that records the number of documents under this category. So the values ​​of these numbers need to be changed dynamically.
With the post.php controller, we can start the process of our data (my controller is not yet a class, so I cannot generate API documents. Because this is not a real MVC architecture.) So before MVC , this can also be more conducive to understanding what MVC is, and how you can apply it and write your own MVC.

The following situations are all assumptions:

$action = "Give me a girlfriend from the sky!"; Let's pass in this controller and see what happens.

Copy code The code is as follows:

require_once( "config/config.php" );
session_start( );
$action = isset( $_GET['action'] ) ? $_GET['action'] : "";
$username = isset( $_SESSION['username'] ) ? $_SESSION['username '] : "";

if( !$username )
{
header("Location: index.php?action=login");
exit;
}

Here we have an important flow control statement switch, which means switch; so when the above $action = "Give me a girlfriend from the sky!"; when switch is passed in, there are only two possibilities, One is on and one is off. There is a bit of a pun here, and some students may see it. hey-hey!

Getting back to the topic: Take a look at how our switch turns these $actions on and off. It’s obvious that I won’t get a girlfriend from the sky, because there is no such switch in the controller, so I can only talk about the code.

Copy code The code is as follows:

switch( $action )
{
case "newPost" :
newPost( );
break;

case "delete" :
delete( ) ;
break;

case "updatePost":
updatePost( );
break;

case "IsDraft":
listDraft( );
break;

case "logout" :
logout( );
break;

case "isPost":
listPost( );
break;

case "diffentCategoryPost":
diffentCategoryPost( );
break;

case "unCategory":
unCategory( );
break;

default :
listPost( );
break;
}

Each switch should define a default switch, so that when we don’t have a girlfriend, we can ensure that we still have gay friends.
How to pass in action?
Let’s look at such a URL, which is the navigation of our background framework. Post.php?action=isPost This is a standard action. Each of our URLs is actually composed of these actions. You can also add other ones. Some parameters into our url, so that we can GET (get the values ​​of these variables) in the method defined in the controller, and then we can have more control.
Okay, when this url reaches our controller, we receive the judgment, and then turn on an isPost switch, so that we can call the following methods. Think about turning on and off the light, turning on the computer, the switch is what we often things to do.
Here we just changed the place.
ok. Let’s look at the following method for this switch.

Copy code The code is as follows:

function listPost( )
{
$results = array( );
$results['pageTitle'] = "Post List" ;
$results['path'] = "Essay";
// set the message
if ( isset( $_GET['error'] ) )
{
If ( $_GET['error'] == "InsertedFailed" ) $results['errorMessage'] = "Failed to add document";
if ( $_GET['error'] == "postDeleteFailed" ) $results['errorMessage'] = "Document deletion failed";
}
if ( isset( $_GET['status'] ) )
{
if ( $_GET['status' ] == "changesSaved" ) $results['statusMessage'] = "The document has been saved!"; Deleted!";
if ( $_GET['status'] == "Inserted" ) $results['statusMessage'] = "You added a new document!";
if ( $_GET[' status'] == "SaveToDraft" ) $results['statusMessage'] = "The document was saved to the draft box!";
}

// Category browsing of documents
$db = MySQL: :getInstance( );
$pagination = new Pagination;
$cat = new Category;
$results['categories'] = $cat->getCategoryList("post");

$pagination->countSQL = "select * from post where type = 'post' " ;
$db->Query( $pagination->countSQL );
$pagination->totalRecords = $db->RowCount( );
$records = $db->HasRecords( $pagination->rebuiltSQL( ) );
if( $records )
{
$results[ 'posts'] = $db->QueryArray( $pagination->rebuiltSQL( ) );
require_once(TEMPLATE_PATH . "/post/post_list.php");
}
else
{
require_once(TEMPLATE_PATH . "/post/post_list.php");
}

}

We define an array, $results = array(); The role of this array is obvious. It will save any data we get from the model, and can also save the special parameters of GET from the url. Then it will be displayed in the template included in our require_once(*****) below, and the path is defined in the path variable.

At the same time we will receive 2 prompt parameters,

error means that there is an error in the operation. It is inevitable for everyone, including computers. Everyone will make mistakes. The key is to admit it. Computers do a good job and they have the courage to admit mistakes.

status; indicates status, which is a successful operation.

$pagination = new Pagination; This class is our pagination class. We pass in a total number to it, and then it will calculate the total number of pages. Each time it jumps to a page, it is equivalent to refreshing once, so everyone The method is to GET (obtain) the value of the page on the url in the constructor, so that we know the current page. At the same time, we regenerated the query statement, followed by a limiting statement, similar to limit $start (starting id), $offset (length); the principle is to give me 10 records starting from this id; I The setting is 10, you can also be more flexible.

$cat = new Category; This class will be discussed in detail later, and it is also a very important classification model. Here we simply obtain all categories under this type and display them in the sidebar. I have completed it. There are pictures and the truth!


In this way, our $results array stores all the data needed for our page. Okay, let's take a look at how our template is output.

Copy code The code is as follows:

 
 
    
         <br>             博客后台管理
            
                       
        
    
            
                
                    
                
                
                    
                    
                
                
                    
                    
                
            

                        
操作

                    

                        

                

                
                 if( isset( $results['statusMessage'] )){echo $results['statusMessage'];}
if( isset( $results['errorMessage'] )){echo $results['errorMessage'];}
?>
                

 

    

         文章(主要用于转载,发布原创博文要通过“随笔”)
    

    
    
      if( isset( $results['posts'] )){
     echo <<            
                
                    
                    
                    
                                  
                    
                    
                

 EOB;
         foreach( $results['posts'] as $post ){
             $time = date("Y-m-d H:i:s", $post['create_time']);
             if( $post['status'] == "1" ){
                 $post['status']  = "发布";
             }    else {
                 $post['status']  = "未发布";
             }
             echo <<
                
                
                
                
                
                    
            
 EOB;
         }
             echo "

                         标题
                    

                         发布

                         状态
                    

                         评论
                    

                         页面

                         浏览
                    

                         操作
                    

                         操作
                    
{$post['title']} ({$time}){$post['status']}{$post['view_count']}{$post['comment_count']}编辑删除
";               
             if( isset( $pagination) ){$pagination->createLinks( ) ;}
     } else {
         echo "当前无内容!";
     }

 ?>  

    

 


 

                        

                    

            

                
                
         
                    logout
                

                

            

                                                                                                                                              "2">
                                                                                                                                                                                                            td>

The above is just to show the data, everyone can do it.



How do we operate this data?

Operation is like a control ability. When I was playing football as a student, I had a strong ability to control the court. I won one championship, one runner-up, and one third place in college football games. I didn't go to senior year, and I also won numerous honors in middle school.

My position is central defender. In this position on the football field, you must have the ability to see the overall situation, strong personal ability, and commanding ability. To put it too far, now you sit on the computer every day Before, these things were gone long ago,
Just some words of experience left. But you must also experience the taste.

My blog has a shortcoming. Every time you perform a read or write operation on the database, you have to refresh it! I know this places a heavy load on the server, but I feel that if you don’t fully understand a new technology and use it blindly, it will only be counterproductive.

So for the time being, I will sacrifice the server’s response time and memory consumption to achieve relative stability!

So I don’t know the overall situation very well, and there are still many unknown areas that I haven’t gotten involved in, such as in-depth ajax, in-depth php, c. . . No more to say.

Okay, let’s see how to CRUD the data!

DELETE Delete

Look at this command first post.php?action=delete&postID=132

When we confirm that we want to delete, there is something to note here. We can first perform a subtraction operation of 1 on the count_child_number field under the category to which the document belongs.

Why? Because I also started to make a logical mistake, I only called this method after deletion, remember! The interesting part of reduceChildNumber() is here, and it has benefited me a lot! It also took me a long time to debug!

So: when your grammar is correct, it may be that your logic is wrong! Or the method is wrong! That's my note! Please see:


Copy code

The code is as follows:

$post = new Post;

$filter['post_id'] = isset ( $_GET['postID'] ) ? ( int )$_GET['postID'] : "";

// !important Decrease the number of articles in this category by 1 before deleting the data

// Otherwise you don’t know the number of articles to delete in that category // I made a logical mistake and deleted the document first, and then checked the category ID of the document; I can never find it because it no longer exists. $post->reduceChildNumber( "category", ( int ) $_GET['postID'] ); $result = $post->delete("post", $filter );


Here we can easily call the delete() method as long as we initialize the model at the top of our article.

CREATE insert
Look at this command first post.php?action=newPost
To be honest, I haven’t inserted it in a long time. hehe! See the control method:



Copy code

The code is as follows:


function newPost( )
 {
    $results['action'] = "newPost" ;
    $results['pageTitle'] = " Add New post" ;
    $results['newPost'] = "true";
    $results['path'] = "随笔» 添加随笔" ;
    $post = new Post;
    $cat = new Category;
    $results['categories'] =  $cat->getCategoryList( "post");
    // 新建文档
    if( isset( $_POST['saveChanged'] ))
    {   
        $post-> storePostFormValues( $_POST );
        $result = $post->insertPost( );
        if( $result )
        {
            $post->addChildNumber( "category", $_POST['category'] );
            header("Location: post.php?action=isPost&status=Inserted");
        }
        else
        {
            header("Location: post.php?action=isPost&error=InsertedFailed");
        }
        // 保存到草稿箱
    } else if( isset( $_POST['saveDraft']) )
    {
        $post = new Post;
        $post-> storePostFormValues( $_POST );
        $post->saveDraft( );
        header("Location: post.php?action=isPost&status=postSaveToDraft");
        // cancel
    } else if( isset( $_POST['cancel'] ))
    {
        header("Location: post.php?action=isPost");
    }
    else
    {
        require_once(TEMPLATE_PATH . "/post/post_edit.php");
    }
 }

我们使用一个模版来同时进行文档的插入和更新。关键就是 isset( ),当我们调用控制器的 newPost 方法时,我们并没有往模版中传入文档。
所以在模版中,我们用 isset() 来做判断时,我们获得了空值,是个好东西;这样我们不会输出任何内容到模版中去。这样,我们等待用户提交表单,在这里,我为了省事,暂时没有对表单进行过滤,不过我留了个后门以后来更新。 好的,假设我们的表单被提交了,(也被你基本的过滤了)。

我们调用 post model中 的 storePostFormValues( ) , storeDiaryFormValues( ); 记得嘛,这个方法把所有的表单内容放入一个数组,在做了基本的类型检查之后,
到这里已经成功一半了。下面就是 insert***()。 这就是mysql 万能数据库操作类的好处,它能帮你处理各种表单,各种类型。当然你如果要求更细,更多,你可以继承它,扩展
它的方法,或新建方法。 到这里离完成还有一步,addChildNumber( )。 当你为你的文档选择分类时,同时也要在相应的分类表中的 count_child_number中加 1 。
如果用户选择将文档放入草稿箱的话,只需插入一个 type = PostDraft 的文档记录。

UPDATE 更新
先看这个指令 post.php?action=updatePost&postID=132
更新首先就要获得这个文档的数据,postID, 同样是 GET方法得到。 这样我们就可以初始化表单中的 value 值了。 isset( ) 在这里起了关键作用,不是嘛?

后面的部分大同小异, storePostFormValues( ) , storeDiaryFormValues( ); 然后你调用 post model update***( ) 。
看代码:

复制代码 代码如下:

function updatePost( )
 {
    $results['action'] = "updatePost";
    $results['pageTitle'] = "Edit post";
    $post = new Post;
    $cat = new Category;
    $results['categories'] =  $cat->getCategoryList("post");
    if( isset( $_POST['saveChanged'] ))
    {
        // do update
        $post->storePostFormValues( $_POST );
        $post->updatePost( );
        header("Location: post.php?action=isPost&status=changesSaved") ;                   
    } else if( isset( $_POST['cancel'] ) )
    {
        header("Location: post.php?action=isPost&status=Cancel");
    }else
    {
        // get the post    
        $postID = isset( $_GET['postID'] ) ?  $_GET['postID'] : " ";
        $results['post'] = $post->getPostByID( $postID );
        require_once(TEMPLATE_PATH . "/post/post_edit.php");
    }

 }

到这里就差不多了,我们实现了几乎所有的基本操作。

几点说明,这些action 有的是导航,有的是生成的,大部分是固定的。自己看着用吧。 下篇说说 分类的事!还有就是这篇博客写完后会放在一个网站上

你如果想要源码学习的话,我会提供下载。谢谢你花这么长时间听我唠叨, 看到这句的人,祝你们 昨天 6,1 快乐,嘿嘿。

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/328065.htmlTechArticle废话不多说了,上一篇有个核心概念就是 give action do something ! 这篇我就用代码来解释这个概念是啥意思,先看我的 post.class.php . 这个文件是...
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template