PHP Imitation Blog Park personal blog (2) database additions to delete _php example

Source: Internet
Author: User
Tags echo date
Needless to say, the last article has a core concept is give action do something!





I'll use the code to explain what this concept means, first look at my post.class.php. This file is our data-tier processing class.





A brief introduction to this model class, which inherits a database base class for common operations such as CRUD, initializes a database object $db each time it is initialized. We use this object to manipulate our data.
There are 2 important methods for data manipulation storepostformvalues (), Storediaryformvalues (), and their 2 methods are the beginning of the data stream.
There are 2 other ways that are interesting, addchildnumber (), Reducechildnumber (), which is responsible for a black-and-black operation when inserting or deleting documents. Because My Documents can be categorized in multiple categories, when working with a document, consider the problem of having a field in the category table that records the number of documents under that category. So change the number of values dynamically.
Together with the post.php controller, we can start the process of our data (my controller is not yet a class, so I can't generate the API documentation.) Because it's not really an MVC architecture. So before MVC, it's also a better way to understand what MVC is, and how you can use it to write your own MVC.

The following scenarios are all hypothetical:

$action = "Give me the next girlfriend in the sky!" "; Let's pass in this controller to see what happens to God horse.

Copy Code code 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 Process Control statement switch, which is the meaning of the switch, so when the above $action = "Give me the next girlfriend in the sky!" "; When you pass in a switch, there are only 2 possibilities, one is open, one is off. Here is a little pun meant, some students may see it. Hey!

To get to the chase: see how our switch switches the $action, it's obvious that there's no girlfriend in the sky, because the controller doesn't have the switch, so it's just a matter of talking about the code.

Copy Code code 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 the default switch so that when you don't have a girlfriend, you can make sure that we have a base friend.
How do I get the action?
To see such a URL, which is our background frame navigation, post.php?action=ispost this is a standard action, we each URL is actually composed of these action, can also add some other parameters to our URL, So we can get the values of these variables in the method defined by the controller, and then we can have more control.
OK, when this URL arrives at our controller, we receive the judgment and then open a isPost switch so we can call the back method, think about the switch light, switch the computer, switch is what we often do.
We just changed a place here.
Ok. Take a look at the following method of this switch.

Copy Code code as follows:



function Listpost ()


{


$results = Array ();


$results [' pagetitle '] = "Post List";


$results [' path '] = ' <a href= '? action=ispost ' > Essay </a> ';


Set the message


if (Isset ($_get[' error '))


{


if ($_get[' error '] = = "insertedfailed") $results [' errormessage '] = "document Add Failed";


if ($_get[' error '] = = "postdeletefailed") $results [' errormessage '] = "Document deletion failed";


}


if (Isset ($_get[' status '))


{


if ($_get[' status '] = = "changessaved") $results [' statusmessage '] = "document Saved!";


if ($_get[' status '] = = "Deleted") $results [' statusmessage '] = "document deleted!";


if ($_get[' status '] = = "Inserted") $results [' statusmessage '] = "You have added a new document!";


if ($_get[' status '] = = "Savetodraft") $results [' statusmessage '] = "Document saved to 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 have defined an array, $results = Array (); This array is obvious in that it will save any data we get from model, or we can save special parameters from the URL. It will then be shown in the template that is contained in require_once below us, and the path is defined within the PATH variable.

At the same time, we will receive 2 cue parameters,

Error, said the operation of errors, anyone is unavoidable, including computers, who will make mistakes, the key is to admit that the computer does a good job, they dare to admit mistakes.

Status Represents a state, which is a successful operation.

$pagination = new pagination; This class is our paging class, we pass in a total quantity to it, and then it will figure out the total number of pages, each jump a page, equivalent to refresh once, so everyone's approach is, in the constructor get (gets) the URL page value, let us know is the current page. At the same time we regenerate the query statement, followed by a restricted statement, similar to the limit $start (the starting ID), $offset (length); The principle is from this ID, give me back 10 records, my setting is 10, you can also be more flexible.
$cat = new Category; This class will be described in detail later, and is also a very important category model. Here we simply get all the categories under this type, shown in the sidebar, I've finished. There is a picture of the truth!




So our $results array stores all the data we need on our page. OK, let's take a look at our template and how it's output.

Copy Code code as follows:



<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "HTTP://WWW.W3.ORG/TR/HTML4/LOOSE.DTD" >


<html>


<head>


<title>


Blog Background Management </title>


<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 "/>


<link rel= "stylesheet" type= "Text/css" href= "Assert/css/blog.css"/>


</head>


<body id= "Posts" >


<table id= "bodytable" border= "0" cellpadding= "0" cellspacing= "0" width= "100%" >


<tr>


<TD id= "Header" colspan= "2" ><div id= "Sitenav" ></div>


<div id= "Blogtitle" >


Arist ' s Blog


</div>


<div id= "Site Title" >


<b><blockquote>hinging there, everything would be fine.</blockquote></b>


</div>


</td>


</tr>


<tr>


<td>


<div id= "Leftnavheader" > Operations </div>


</td>


<TD class= "Navheaderrow" >


<ul id= "Topnav" >


<li><a href= "Post.php?action=ispost" > Essays </a></li>


<li><a href= "Article.php?action=isarticle" > Articles </a></li>


<li><a href= "Diary.php?action=isdiary" > Diary </a></li>


<li><a href= "Comment.php?action=iscomment" > Review </a></li>


<li><a href= "Photo.php?action=isphoto" > Photo </a></li>


</ul>


<div id= "Subnav" >


Current Position: <?php if (isset ($results [' path ']) echo $results [' path '];?>


</div>


</td>


</tr>


<tr>


<TD class= "Navleftcell" >


<div class= "Left_nav" >


<ul id= "Linksactions" >


<li><a href= "article.php?action=newarticle" >» Add new articles </a></li>


</ul>


</div>


<div id= "Categoriesheader" class= "Leftnavheader" >


Classification


</div>


<div class= "Left_nav" >


<ul id= "Linkscategories" >


<li><a href= "category.php?action=listcat&type=article" >[Edit category]</a></li>


<li><a href= "Article.php?action=isarticle" >[all classifications]</a></li>


<li><a href= "Article.php?action=uncategory" >[not categorized]</a></li>


<?php


if (Isset ($results [' categories ']) &&! empty ($results [' categories '])) {


foreach ($results [' categories '] as $category) {


Echo <<<eob


<li><a href= "article.php?action=diffentcategoryarticle&catid={$category [' category_id ']}" >{$ category[' name '} ({$category [' Count_child_number ']}) </a></li>


EOB;


}


}


?>


</ul>


</div>


</td>


<TD id= "Body" >


<div id= "Main" >


<div id= "Editor_messages" >


<!--display Tips-->


<?php


if (Isset ($results [' StatusMessage ']) {echo $results [' StatusMessage '];}


if (Isset ($results [' errormessage ']) {echo $results [' errormessage '];}


?>


</div>


<div id= "Editor_results" >


<div id= "Editor_results_header" class= "Collapsibleheader" >


<span id= "Editor_results_headertitle" > article (mainly used for reprint, publish original blog to pass "essay") </span>


</div>


<div id= "Editor_results_contents" >


<?php


if (Isset ($results [' posts '])) {


Echo <<<eob


<table id= "Listing" class= "Listing" cellspacing= "0" cellpadding= "0" border= "0" style= ' width:98%; ' >


<tr style= "Text-align:center" >


<th valign= "Bottom" >


Title


</th>


<th width= "style=" "Text-align:center" >


Publish <br/>


State


</th>


<th valign= "Bottom" width= "style=" "Text-align:center" >


Comments


</th>


<th width= "style=" Text-align:center ">


Page <br/>


Browse


</th>


<th valign= "Bottom" width= "style=" "Text-align:center" >


Operation


</th>


<th valign= "Bottom" width= "style=" "Text-align:center" >


Operation


</th>


</tr>





EOB;


foreach ($results [' posts '] as $post) {


$time = Date ("y-m-d h:i:s", $post [' create_time ']);


if ($post [' status '] = = "1") {


$post [' status '] = "publish";


} else {


$post [' status '] = ' <b> not released </b> ';


}


Echo <<<eob


<tr id= "entry_{$post [' post_id ']}" class= "Alt" >


<TD style= "Text-align:left" >{$post [' title ']} ({$time}) </td>


<TD style= "Text-align:center" >{$post [' Status ']}</td>


<TD style= "Text-align:center" >{$post [' View_count ']}</td>


<TD style= "Text-align:center" >{$post [' Comment_count ']}</td>


<TD style= "Text-align:center" ><a href= "article.php?action=editarticle&postid={$post [' post_id ']}" > Edit </a></td>


<TD style= "Text-align:center ><a href=" javascript:if (' delete this document from database? ') ==true) {window.location= ' article.php?action=delete&postid={$post [' post_id ']} ';} ' > Delete </a></td>


</tr>


EOB;


}


echo "</table>";


if (Isset ($pagination)) {$pagination->createlinks ();}


} else {


echo "Not currently content!" ";


}





?>





</div>


</div>





<span id= "Currentpostid" style= "Display:none;" ></span>





</div>


</td>


</tr>


</table>


<div id= "Blog_top_nav_block" >


<div id= "Site_nav" >


</div>


<div id= "Login_area" >


<span id= "Span_userinfo" ><b><?php echo $_session[' username ';?> </b> <a href= "? action= Logout ">logout</a></span>


</div>


<div class= "Clear" ></div>


</div>


<table id= "Footer" border= "0" cellpadding= "0" cellspacing= "0" width= "100%" >


<tr>


<TD colspan= "2" >


<div>


©<?php echo Date ("Y", Time ());?> arist


</div>


</td>


</tr>


</table>


</body>


</html>


The above only shows the data, everyone will ah.

How do we operate the data?

Operation, it is like a control ability. Students play football, I have a strong ability to control the stadium, the University football tournament won 1 times, 1 runners-up, 1 third runner-up, senior did not go, middle school is countless honors.

My position is Zhongwei, in the football field, this position, you have to have strategists the overall ability, also must have the very strong personal ability, but also has the command ability; pull far, now sit in front of the computer everyday, these things also long ago,

There's just a few experiences left. But the taste, you must also experience.

I have a flaw in this blog, every time you read and write to the database, you have to refresh Ah! I know this load on the server is very large, but I think if a new technology you do not fully understand, blindly use, will only backfire.

So temporarily I still sacrifice server response time, memory consumption, to obtain a relatively stable!

So I am not very understanding of the overall situation, there are many unknown areas are not involved, such as in-depth Ajax, in-depth php,c ... I don't have much to say.

OK, let's see how to crud the data!

Delete deletion
Look at this instruction first post.php?action=delete&postid=132

When we confirm that we want to delete, there is a place for attention here, we can first of the document to belong to the category of Count_child_number this field to do a minus 1 action.

Why? Because I also began to make a logical mistake, delete after I call this method, remember! Reducechildnumber () interesting place is here, let me benefit! Also let me debug the N long!

So: When your grammar is correct, it may be your logic is wrong! Or the method is wrong! This is my comment! Please see:

Copy Code code as follows:

$post = new Post;
$filter [' post_id '] = isset ($_get[' PostID '])? (int) $_get[' PostID ']: "";

!important reduce the number of articles under this category by 1 before data is deleted
Otherwise you don't know the number of articles deleted under that category
I made a logical mistake. First delete the document, and then look at the document's category ID; never to be found, because no longer exists.
$post->reducechildnumber ("category", (int) $_get[' PostID ');

$result = $post->delete ("Post", $filter);

Here we can easily invoke the delete () method simply by initializing the model on top of our article.

CREATE Insert
Look at this instruction first Post.php?action=newpost
To tell you the truth, I haven't inserted it for a long time. Oh! See Control method:

Copy Code code as follows:



function Newpost ()


{


$results [' action '] = "newpost";


$results [' pagetitle '] = "Add New post";


$results [' newpost '] = "true";


$results [' path '] = ' <a href= '? action=ispost ' > Essay </a>»<span> add essay </span> ';


$post = new Post;


$cat = new Category;


$results [' categories '] = $cat->getcategorylist ("post");


New Document


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");


}


Save to draft box


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");


}


}


We use a template to simultaneously insert and update the document. The key is Isset (), and when we call the controller's Newpost method, we don't pass the document on to the stencil.
So in the template, we use Isset () to make judgments, we get null value, is a good thing, so we do not output any content to the template. In this way, we wait for the user to submit the form, here, I for the sake of convenience, temporarily did not filter the form, but I left behind a backdoor to update. OK, let's say our form has been submitted, (and it's basically filtered by you).

We call the Storepostformvalues () in post model, storediaryformvalues (); Remember, this method puts all the form contents into an array, and after doing the basic type check,
Half the success has been achieved here. Here is insert*** (). This is the benefit of the MySQL Universal database Operations class, which can help you deal with various forms, various types. Of course if you ask for finer, more, you can inherit it, extend
Its method, or create a new method. Here is a step closer to completion, Addchildnumber (). When you select a category for your document, add 1 to the Count_child_number in the corresponding category table.
If the user chooses to place the document in the draft box, simply insert a type = Postdraft document record.

Update updates
Look at this instruction first post.php?action=updatepost&postid=132
The update will first get the data for this document, PostID, and the Get method. So we can initialize the value values in the form. Isset () plays a key role here, doesn't it?

The back part is similar, storepostformvalues (), storediaryformvalues (); Then you call the Post Model update*** ().
Look at the code:

Copy Code code as follows:



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");


}





}


It's about the same here, we've achieved almost all the basic operations.

Some of these are navigation, some generated, and most of them fixed. Look at it yourself. The next chapter is about classification! And this blog will be placed on a Web site when it's finished.

If you want to learn the source code, I will provide downloads. Thank you for taking so long to listen to my nagging, see this sentence of people, I wish you 6,1 happy yesterday, hehe.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.