Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to add, change and delete PHP database

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article introduces the relevant knowledge of "how to add, change and delete PHP database". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Take a look at my post.class.php. This file is our data layer processing class.

A brief introduction to this model class, which inherits a database base class to do crud and other common operations, each initialization will initialize a database object $db. We use this object to manipulate our data.

There are two important methods storePostFormValues () and storeDiaryFormValues () for data manipulation, and their two methods are the beginning of the data flow.

There are also two interesting methods, addChildNumber () and reduceChildNumber (), which are responsible for a black box operation when inserting or deleting a document. Because my documents can be classified in multiple categories, one problem to consider when manipulating documents is that there is a field in the category table that records the number of documents under that category. So change the values of these numbers dynamically.

With the post.php controller, we can start the flow of our data (my controller is not yet a class, so I can't generate an API document. Because this is not a real MVC architecture yet. So before MVC, this also makes it easier to understand whether MVC is god horse Dongdong, and how you use it to write your own MVC.

The following scenarios are hypothetical:

$action = "give me a girlfriend from the sky!" Let's pass in this controller to see what will happen.

The copy 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 in the sky!" When switch is introduced, there are only two possibilities, one is on, the other is off. It's a bit of a pun here, as some students may see. Hey!

Back to the point: look at how our switch switches on and off these $action, it's obvious that there won't be a girlfriend in the sky for me, because there's no such switch in the controller, so let's just talk about the code.

The copy 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

}

Every switch should define a default switch so that when we don't have a girlfriend, we can make sure we still have gay friends.

How to pass in action?

Let's take a look at such a url, that is, the navigation of our background framework. Post.php?action=isPost is a standard action. Each of our url is actually composed of these action, and we can also add some other parameters to our url, so that we can GET (get the values of these variables) in the method defined by the controller, and then we can have more control.

Well, when the url reaches our controller, we receive the judgment, and then turn on an isPost switch, so we can call the following method, think about turning on and off the lights, turning on and off the computer, the switch is what we often do.

We just changed places here.

Ok . Let's take a look at the following method of this switch.

The copy 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'] = "the document is saved!"

If ($_ GET ['status'] = = "Deleted") $results [' statusMessage'] = "document deleted!"

If ($_ GET ['status'] = = "Inserted") $results [' statusMessage'] = "you added a new document!"

If ($_ GET ['status'] = = "SaveToDraft") $results [' statusMessage'] = "the document is saved to the draft box!"

}

/ / classified 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 (); this array is very useful, and it will hold any data we get from model, as well as special parameters of GET from url. It will then be shown in the template contained in require_once (*) below, with the path defined in the path variable.

At the same time, we will receive two prompt parameters.

Error, said that operation errors are inevitable for anyone, including computers, everyone will make mistakes, the key is to admit that the computer has done a good job, they have the courage to admit mistakes.

Status; represents status, which is a successful operation.

$pagination = new Pagination; this class is our paging class, we pass in a total number of pages to it, and then it will calculate the total number of pages, each jump to a page, equivalent to a refresh, so what we do is to GET (get) the value of page on the url in the constructor to let us know which page is current. At the same time, we regenerate the query statement, followed by a limited statement, similar to limit $start (starting id), $offset (length); the principle is from this id, then give me 10 records; my setting is 10, you can also be more flexible.

The class $cat = new Category;, which is also a very important category model, will be described in more detail later. Here we simply get all the categories under this type, which are shown in the sidebar, which I have finished. There is a picture and a truth!

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

The copy code is as follows:

Blog background management

Arist's Blog

Hinging there, everything will be fine.

Operation

Essays

Article

diary

Comment

photo

Current location:

»add a new article

classification

[edit category]

[all categories]

[unclassified]

Articles (mainly used for reprinting, original blog posts should be published through "essays")

Logout

©Arist

The above is just a display of data, everyone can.

How do we manipulate the data?

Operation is like a kind of control ability. When I played football when I was a student, I had a strong ability to control the court. I won 1 championship, 1 runner-up, 1 runner-up in college football match, and I didn't go to my senior year, and there were countless honors in middle school.

My position is the centre-back, in the football field, this position, you must have the ability to view the overall situation, but also have a strong personal ability, and command ability; pull too far, now sitting in front of the computer every day, these things are long gone

There is only some experience left. But you must also have experienced the taste.

There is a disadvantage in my blog. Every time you read and write to the database, you have to refresh it. I know it's a heavy load on the server, but I think if you don't fully understand a new technology and use it blindly, it will only backfire.

So for the time being, I am sacrificing the server's response time and memory consumption to achieve a relative stability!

So I don't know much about the overall situation, and there are many unknown areas that have not been involved, such as going deep into ajax, going deep into php,c. Say no more.

All right, let's see how to CRUD the data.

DELETE deletion

Take a look at this instruction post.php?action=delete&postID=132 first.

When we confirm that we want to delete, here is a note that we can first subtract 1 from the count_child_number field under the category to which the document belongs.

Why? Because I also started to make a logic mistake, I didn't call this method until I deleted it, remember! What's interesting about reduceChildNumber () is here, which benefits me a lot! Also let me debug for a long time!

So: when your grammar is correct, your logic may be wrong! Or the wrong way! This is my comment! Please look at:

The copy code is as follows:

$post = new Post

$filter ['post_id'] = isset ($_ GET [' postID'])? (int) $_ GET ['postID']: ""

/ /! important subtracts the number of articles under this category by 1 before data deletion

/ / otherwise you don't know the number of articles deleted under that category

/ / I made a logical mistake to delete the document first, and then look up the classification of the document. ID; will 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 by initializing the model at the top of our article.

CREATE insertion

Take a look at this instruction post.php?action=newPost first.

To be honest, I haven't plugged in for a long time. He he! Look at the control method:

The copy code is as follows:

Function newPost ()

{

$results ['action'] = "newPost"

$results ['pageTitle'] = "Add New post"

$results ['newPost'] = "true"

$results ['path'] = "essay »add essay"

$post = new Post

$cat = new Category

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

/ / create a 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 insert and update the document at the same time. The key is isset (). When we call the controller's newPost method, we don't pass the document into the template.

So in the template, when we use isset () to make a judgment, we get a null value, which is a good thing; so we don't output anything to the template. In this way, we wait for the user to submit the form, and here, to save trouble, I didn't filter the form for the time being, but I left a back door for later update. OK, suppose our form is submitted (and basically filtered by you).

We call storePostFormValues (), storeDiaryFormValues () in post model; remember, this method puts all the contents of the form into an array, after doing basic type checking

We're halfway there. Here is insert*** (). This is the advantage of mysql universal database operation class, which can help you deal with all kinds of forms and types. Of course, if you ask for more detail and more, you can inherit it and extend it.

Its method, or a new method. There is still one step to completion, addChildNumber (). When you choose a category for your document, add 1 to the count_child_number in the corresponding classification table.

If the user chooses to put the document in the draft box, simply insert a document record with type = PostDraft.

UPDATE update

Take a look at this instruction post.php?action=updatePost&postID=132 first.

The first thing to update is to get the data of the document, postID, which is also obtained by the GET method. So we can initialize the value value in the form. Isset () plays a key role here, doesn't it?

The latter part is more or less the same, storePostFormValues (), storeDiaryFormValues (); then you call post model update*** ().

Look at the code:

The copy code is 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")

}

}

This is the end of the content of "how to add, change and delete PHP database". Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report