PHP Faux Blog Garden Personal blog (2) database add to delete _php tutorial

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

In this article I use the code to explain the meaning of this concept, first look at my post.class.php. This file is our data layer processing class.

Simply introduce this model class, which inherits a database base class to do common operations such as CRUD, and 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 flow.
There are 2 more interesting methods, Addchildnumber (), Reducechildnumber (), which are responsible for a black-out operation when inserting or deleting a document. Because My Documents can be categorized in multiple categories, there is a problem when working with documents that the Category table has a field that records the number of documents in that category. Therefore, the values of these numbers are changed dynamically.
With the post.php controller below, we can begin the process of our data (my controller is not yet a class, so the API documentation cannot be generated.) Because this is not really the MVC architecture. So before MVC, this would be a better way to understand how MVC is God's horse, and how you can apply it and write your own MVC.

The following scenarios are hypothetical:

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

Copy the 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 = "The sky off the next girlfriend to me!" "; When you pass in a switch, there are only 2 possibilities, one is on and one is off. Here is a bit of a pun, some students may have seen it. Hey!

Anyway: see how our switch switches these $action, it is clear that the sky will not drop a girlfriend to me, because the controller does not have this switch, so can only talk about the code.

Copy the 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 there is no girlfriend, you can make sure we have a friend.
How do I pass in an action?
To see such a URL, that is, our background frame navigation, post.php?action=ispost this is a standard action, we each URL is actually composed of these actions, we can also add some other parameters to our URL, So we can get (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, then open a isPost switch, so we can call back the method, think switch lights, switch computer, switch is what we often do.
Here we are just changing a place.
Ok. Take a look at the following method of this switch.

Copy CodeThe 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 '] = "document addition 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 the Drafts box!";
}

Category browsing for 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 (); This array is obviously useful, it will save any data we get from the model, or we can save special parameters for get from the URL. It is then shown in the template contained in the require_once below (* * * * * * * * * *), where the path is defined in the PATH variable.

At the same time we will receive 2 prompt parameters,

Error, indicating that the operation has been wrong, anyone can be unavoidable, including computers, who will make mistakes, the key is to admit that the computer is doing well, 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, then it will figure out the total number of pages, each jump to a page, the equivalent of refreshing one time, so everyone's practice is, in the constructor get (GET) URL page value, let us know is the current page. At the same time we re-generated the query statement, followed by a restrictive statement, similar to the limit $start (the starting ID), $offset (length); The principle is from this ID, back to me 10 records, my set is 10, you can also be more flexible.
$cat = new Category; This class will be described in detail later, and is a very important classification 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 for our page. OK, let's see how our templates are exported.

Copy the Code code as follows:



<BR> Blog Background Management


















Arist ' s Blog


hinging There, everything'll be fine.



Operation


  • Essay

  • Article

  • Diary

  • Comments

  • Photo



Current Position:




  • » Add New articles




Classification



  • [Edit category]

  • [All Categories]

  • [Uncategorized]

  • if (Isset ($results [' categories ']) && empty ($results [' categories '])) {
    foreach ($results [' categories '] as $category) {
    Echo <<<>
  • {$category [' name ']} ({$category [' Count_child_number ']})

  • EOB;
    }
    }
    ?>







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



article (mainly for reprint, publish original blog to pass "essay")


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















not published

<>











EOB;foreach ($results [' posts '] as $post) {$time = Date ("y-m-d h:i:s", $post [' create_time ']);if ($post [' status '] = = "1") {$post [' status '] = "release";} else {$post [' status '] = '";}Echo << EOB;}echo "

Title

Release

State

Comments

Page

Browse

Operation

Operation
{$post [' title ']} ({$time}) {$post [' status ']} {$post [' View_count ']} {$post [' Comment_count ']} Edit Delete
";
if (Isset ($pagination)) {$pagination->createlinks ();}
} else {
echo "No content at this moment!" ";
}

?>












logout









© Arist




The above is just a display of data, everyone will ah.

How do we manipulate this data?

Operation, it is like a kind of control ability. Student time to play football, I have a strong control of the stadium, the University football match took 1 times champion, 1 times runner-up, 1 third runner-up, senior not to go, high school is countless honors.

My position is the central defender, in the football field, this position, you must have the looking at overall ability, also must have the very strong individual ability, as well as the command ability, pulls the far, now every day sits in front of the computer, these things also already had not already,

There is some experience left. But the taste of it, you must also experience.

I have a disadvantage of this blog, every time you read and write to the database, you have to refresh Ah! I know that the load on the server is very large, but I think if a new technology you are not completely thoroughly understand, blindly use, will only backfire.

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

So I do not know the overall situation, there are a lot of unknown areas are not involved, such as deep Ajax, deep php,c ... Not much to say.

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

Delete Deletes
Look at this command first post.php?action=delete&postid=132

When we confirm that we want to delete, here is a note, we can first of this document belongs to the classification of the Count_child_number this field to do a minus 1.

Why? Because I also started to make a logic error, delete after I call this method, remember! Reducechildnumber () interesting place is here, let me benefit! Also let me debug for n long!

So: When your grammar is right, it may be your logic is wrong! or the wrong way! This is my comment! Please see:

Copy the 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
Or you don't know the number of articles that are deleted from that category.
I made a logical mistake. First delete the document, and then check the document's classification ID; never found, because no longer exists.
$post->reducechildnumber ("category", (int) $_get[' PostID '));

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

Here we simply initialize the model on top of our article to call the Delete () method easily.

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

Copy CodeThe code is as follows:
function Newpost ()
{
$results [' action '] = "newpost";
$results [' pagetitle '] = "Add New post";
$results [' newpost '] = "true";
$results [' path '] = "Essays»Add an essay" ;
$post = new Post;
$cat = new Category;
$results [' categories '] = $cat->getcategorylist ("post");
New Document
if (Isset ($_post[' savechanged '))
{
Storepostformvalues, $post ($_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;
Storepostformvalues, $post ($_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 insert and update documents at the same time. The key is Isset (), and when we call the controller's Newpost method, we don't pass the document to the template.
So in the template, we use Isset () to make judgments, we get a null value, is a good thing, so we will not output any content into the template. In this way, we wait for the user to submit the form, here, I do not filter the form for the sake of convenience, but I left a backdoor to update. OK, let's say our form was submitted (and you're basically filtering it).

We call Storepostformvalues () in the post model, storediaryformvalues (); Remember, this method puts all the form contents into an array, and after doing the basic type checking,
It's half done here. Here is insert*** (). This is the benefit of MySQL Universal database operation class, it can help you to handle various forms, various types. Of course if you ask for finer, more, you can inherit it, extend
Its method, or the new method. There is one more step to be done here, Addchildnumber (). When you select a category for your document, also add 1 to the Count_child_number in the corresponding classification table.
If the user chooses to put the document into a scratch box, simply insert a document record of type = Postdraft.

Update updates
Look at this command first post.php?action=updatepost&postid=132
The update is the first to obtain the data of this document, PostID, is also obtained by the Get method. This allows us to initialize the value values in the form. Isset () plays a key role here, doesn't it?

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

Copy the 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 almost there, and we've achieved almost all of the basic operations.

A few points indicate that these actions are navigation, some of which are generated, and most are fixed. See for yourself. The next article about the classification of things! And this blog post will be put on a website after writing

If you want to learn from the source, I will provide the download. Thank you for taking such a long time to listen to my nagging, see this sentence of the people, I wish you 6,1 happy yesterday, hey.

http://www.bkjia.com/PHPjc/328065.html www.bkjia.com true http://www.bkjia.com/PHPjc/328065.html techarticle 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 ...

  • 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.