Create your own CRUD app with PHP & MySQL (Part 2)

Picking up from where we left off, we need to start by creating some HTML to display the data we’ve stored in the $results variable. You can always modify this to suite your project. I’ll be using a table structure.

Let’s go through what’s happening here. Right after the opening tbody tag I create a for loop.

Essentially, a loop is a piece of code you want to use repeatedly; hence the term loop. For each result from the database I store it in a variable called $entry. Then to go a step further I can target specific fields by using the namespace separator or sometimes called the “arrow operator”(->).

The namespace separator allows you to target objects within objects. By using the loop we can “loop” through all the results from the database and they will have the own rows in the table. Ensure that the loop is closed after the closing tr tag to prevent data spilling out incorrectly.

You’ll also notice that there are two links (Edit & Delete) that handle editing and deleting specific entries. The syntax is simple and if you understand how one works, the other one makes perfect sense. Let’s look at the Edit link:

<a href=”edit.php?id=<?php echo $entry->id; ?>”>Edit</a>

This link will go to edit page and display the editable data related to the id that we echo out. Delete link simply deletes an entry by it’s id. Please note that these two links are inside the for loop, that way we get a edit and delete button for each entry in the database. The last link, which is out side of the loop is an add link that goes to an add.php page where you can input new data instead of going to the actual database manager to insert data.

The first line includes our db.php file which establishes a connection to our database. Next we create an if statement to see if an id was also passed in the link and if it exists in our database, then we continue.

Next we create a prepare statement. A prepare statement “prepares” a SQL statement to be “executed” by the PDO:execute method. Prepare statements help to prevent against hacks and injection attacks because we never clearly quote values, parameters etc. we utilize user-input and bind them to our statements.

So in our case our prepare statement is: ‘DELETE FROM games WHERE id = :id’. The id with a colon is our user-input, in our case the id we pass along in the link. In the next line we bind id to the id we passed in the link, so if the id we passed was 3, we will be deleting the entry in our database that has an id of 3.

While we bind our values we also specify what kind of data it is. In our case it’s an integer so we use PDO::PARAM_INT. Next we need to execute our SQL statement, using the execute method. Once it has been executed, we want to redirect the user to the index.php page the best and fastest way is by using header(‘Location: index.php’)exit;. This process happens so quickly you barely even notice it. Now we’ll move on to the edit.php page.

The first line includes our db.php file and our filter-wrapper.php file. As you already know, the db.php file establishes a connection with the database, the filter-wrapper on the other hand does something totally different. It checks to see what wrappers your version of php has, if it’s missing some it creates and defines them. Depending what version you have newer or older I think it best always to keep a copy handy, as may not need it when creating the code but your client or wherever it may be hosted might need it if they’re running an older version of php. In the next line we create an array and store it in a variable called $errors; this will help us with our validation. Next we check if an id has been passed along with the link; if not we redirect them to the index page using header(‘Location: index.php’)exit;.

If an id is passed along we need to make sure that validate that the user and inputted data we can store in our database, and that the input is not harmful to our database and will neither compromise it’s integrity. We need to sanitize our inputs. This is where our filter wrapper shines as it holds all the filters we need to check if the user’s input is valid. We’ll use filters that appropriately match our desired input; eg.

If we expect a string our filter would be FILTER_SANITIZE_STRING, for a integer, FILTER_SANITIZE_INT and so on. Once we’ve taken care of filtering our input fields, we need to do some basic validation. Remember that empty $errors array we created? The next thing we need to get some basic validation going is to create an if statement. If a particular field is empty we add that to the errors array. Once we have that done for all fields and we check if the data is valid we can update the database by using the prepare statement again like we did for the delete.php file. We bind all our inputs to the fields in the database then execute our SQL statement.

Now we need to ensure that when the page is visited the data that was previously stored in the database shows up in their specific fields; this helps if the user just wants to make a slight edit like a name change or correct a spelling error etc. The first part is done in this remaining code block; the rest is done within the form. What comes next in our code is another prepare statement; we will select all fields by id. Next, we bind the id we passed along in the edit.php link and execute the query. Since we only need to display one database entry, we don’t need a for loop; so variables for each field is fine in this case.

Now we can move to the little bits of php in our html. For our form element, ensure that you echo the id when you are typing the link for the action, and set the method to post. Next, the input fields; This is very easy just echo the different variables in their appropriate values. For the basic valid you can use whatever element you like to display your error message; a strong tag, p tag, whatever. I used a label tag. To get the validating going you need to wrap that label or strong or p tag in an if statement and check if it’s appropriate error is in the $errors array. If it is we display that error message, and that’s it for the edit.php page. Now let’s take a look at the add.php page.

You can see it’s very similar to the edit.php page, with regards to validation and such. Where it becomes different is the SQL statement; instead of updating or deleting data we are inserting data into the database hence we use INSERT. We also do not insert a new id as we want that to auto-increment as we have set in our database. The rest looks similar; we bind our inputs and execute our SQL statement. Our html is the same from the edit.php page as we are doing basic validation. That is how to create a CRUD app in php; the principles can be expanded to how large or how small your desired project is, and it is very secure from rainbow table hacks and SQL injection attacks.

Picking up from where we left off, we need to start by creating some HTML to display the data we’ve stored in the $results variable. You can always modify this to suite your project. I’ll be using a table structure. <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <link href="styles/theme.css" rel="stylesheet"/> <title>PHP & MySQL</title>\ </head> <body> <div id="wrapper"> <table> <thead> <th>Title</th>...

In the first two parts of this series, we created the data layer that will hold the polling data and established methods for setting the variable values and reading from the database tables. In this part, we will build the methods that will write new polls and answers to the tables. The addPoll method adds a new record to the devdrive_polls table and returns a Boolean value that signals if the record was added successfully. function addPoll($aArgs) { // add a poll record $sql = "LOCK TABLES devdrive_polls...

A SQL injection is a common programming error the consequences of which can be really devastating. Many successful hacking attacks start when a hacker discovers a vulnerability that gives an opportunity to inject SQL code. When an SQL injection occurs, the structure of an SQL query is compromised and as a result you are left at the mercy of the potential hackers. If there is a vulnerability found, hackers can exploit it to gain access not only to your site and database but in extreme cases also to your corporate...

So far we've created some basic PHP pages and added some simple authentication. Today we're going to going to build on that by adding database support. This will allow us to add proper authentication to our application and start saving tasks. I should also note that I am currently writing PHP in-line and not using functions (or object orientated PHP) I will tidy this up in the next tutorial and spend more time explaining it and what it's benefits are. Last week ... Last week we installed XAMPP, so you should...

In our last session, we looked at the process of entering information on ad banners and ad clients, as well as generating ad activity reports. This week, we examine how to retrieve a random banner ad. We will also learn how to delete, activate and deactivate ads and clients. The getRandomAd() function retrieves a random ad by using the PHP rand() function. The function returns the ad’s primary key ID, client ID, title, URL and redirect path. The function also updates the activity table for this banner...

In our last PHP Ad Tracker lesson, we constructed the database tables for our ad banner application. Now we are ready to construct the data object that will hold the variables and functions that will display, add, edit and delete the data in those tables. Once we name all of the variables and functions, we will start applying the code to them. Variables: The data object class will hold two variables: one to hold the banner ad ID number from the ads table, and one to hold the database connection information....

In the previous lesson, we examined the basic functions of our banner ad tracking system, including the retrieval of records for both banner ads and advertisers. In this lesson, we will look at the functions responsible for generating reports and manipulating the data in the ads table and advertiser table. The getClientsList() function retrieves active client records and sorts them alphabetically by client name: function getClientsList() { // get clients from db $sql = "SELECT ad_client_id,...

Introduction ... I’m going to tell you a story, its about love, death and re-birth... Or something In the beginning there was a young html element called <table>. He had one purpose in life, to display data and life was good. But before long though he had been corrupted, his masters used him to define layout and structure. Things he was not originally designed to do, and so began the dark ages of web design. Then one day, there came a young knight called CSS, and with him he brought light to designers...

About

DeveloperDrive.com is a blog about web development from the makers of the popular web design blog WebdesignerDepot.com
Founded in 2011, we focus on the latest trends, tutorials, opinion articles as well as tips and tricks to empower our readers to become better web developers.