PHP tutorial to list and insert a products in the database
PHP tutorial to list and insert a products in the database
This tutorial is aimed to developers that know PHP. The goal is simple, to create a proper project as fast as possible and as scalable as possible.
Ingredients
- PHP 5.6 or higher must be installed and running with a webserver.
- You could install a WAMPServer, LAMP or similar.
- PHP’s Composer installed and running.
- knowledge of PHP. It is not a course of PHP
- We use PINGENDO 4 (free) for the design of the page. But you could design or use another editor or do it from scratch
- MySQL must be installed. 5.6 or Higher.
- An php editor. I use PHPStorm (paid application) but it is possible to use any editor.
- An IDE for MYSQL. I use Mysql Workbench (free).
- 45 minutes.
Stage 1, creating the project.
- First, let’s create a new folder inside your web folder. Example c:\wamp\htdocs\
I will use the next folder
D:\Dropbox\www\currentproject\BladeOneTut1
- Open the folder with a shell (cmd or terminal) and let’s run the next command
So I used the next command to create the folder(windows). Or you could use a GUI to create the folder.
mkdir D:\Dropbox\www\currentproject\BladeOneTut1
Then,let’s go inside the folder
cd folder_name
and inside it, runs the next command:
composer init
Then, add the information about your product, for example, your name, stability, package (I used “project”), license (I used “MIT”)
Then, I added the next libraries (interactively, we don’t need to indicate the version):
- eftec/bladeone
- eftec/daoone
And that’s it, it will create the file composer.json
Then, let’s run the next command
composer udate
It will create the folder vendor and a file called composer.lock
And done (this stage).
Stage 2 Creating some views
For this part of the project, we will use Pingendo, it is a free aplication to create html using bootstrap 4
Starting Pingendo
It is the interface of Pingendo: (we want to create a single page File->New Blank File, not a pingendo project)
We want to create two pages: a page with a form and with a table.
Creating the form with Pingendo
First, let’s create the form
I created a form with a title, two fields (name and price) and a submit button. But let’s check if everything is ok.
- The form must use the method=”POST”
- the first textfield must have a name. I will use “frm_name”
- the second textfield must have a name. I will use “frm_price”
- The button must have a name. I will use “frm_button”.
And, apparently it’s ok.
Creating the table
And now, let’s create the table with Pingendo (create a new blank page)
It is the initial table
And I changed the header of the table
Note: We don’t need to change the values.
Stage 2, done.
Stage 3, Template Initial
For the next exercise, we will use the next library:
It’s already loaded (we loaded with composer)
Let’s create a first php file in the root folder of the project.
I will call it first_tut.php
So, what it’s doing?
- It’s loading an autoload (included by Composer). It avoids to add “include” manually.
- It’s create a new instance of the library called BladeOne. It requires two folders, the /view and /compile. Folders that we don’t have right now.
- We will run a temmplate (not yet created called example.tutorial) and, for data, we will use an empty array.
then, we will run (using the browser) and It will show the next screen:
- It fails because it doesn’t found the template.
So, let’s add the template.
Create the next folders view and compile, so your project should look like this:
? vendor. . . . . . . ? some files…. . . . . . . ? composer. . . . . . . ? eftec? view? compile? first_tut.php? composer.json? composer.lock
Then, let’s modify the code a bit and run it again
So, our template must be inside a file called view/example/tutorial.blade.php
So, let’s put it inside.
? vendor. . . . . . .? some files…. . . . . . .? composer. . . . . . .? eftec? view. . . . . . . ? example. . . . . . .. . . . . . .? tutorial.blade.php? compile? first_tut.php? composer.json? composer.lock
and let’s write the next text insie the file tutorial.blade.php
note: I renamed the file as first_tut2.php,, you don’t need to do that.
And done.
Stage 4 Database
Connecting
Let’s open Mysql Workbench
We could create a new connection or use a previous connection. Pick one.
Creating a new database (optional)
For to create a new database, we will click on the icon (indicate as 1), then we will put a name of the database, I will use bladeonetut1 but you could use any name (lowercase). Then, click on the button APPLY (3) and that’s it.
Creating a table
Now, we will create the table called products
- Click on the button (on the image, it’s marked as 1).
- Write the name of the table (2). I will use products
- Then, let’s add some columns to the table (4). If for some reason, the columns are not visible, then resize the output window (3) or press the arrow icons (3). We will use the next columns: 3.1 idproduct (integer) and Auto Increment (5) 3.2 name (varchar(45)) 3.2 price (decimal(9,2))
- Finally, click on Apply (6)
Reading the table
Now, with the table, we could see the information.
Don’t close Workbench, we will use it later.
Stage 4,done.
Stage 5 Insert Form
We will create a new file in the root folder called insert.php
This page will have two stages, when we open and when we click on the button. For the database, we will select the correct database. In my case, the database is at localhost, the user is root, the password is abc.123 and the database (created in Stage 4) is bladeonetut1
We will also create a new template called insert, in the folder product
So, we will create the folder product and the file insert.blade.php
? vendor. . . . . . .? some files…. . . . . . .? composer. . . . . . .? eftec? view. . . . . . .? example. . . . . . . . . . . . . .? tutorial.blade.php. . . . . . .? product. . . . . . . . . . . . . .? insert.blade.php? compile? first_tut.php? insert.php? composer.json? composer.lock
Inside insert.blade.php we will paste the content of the first page created using Pingendo (stage 2)
And if we run the project, it will show the next screen:
Now, let’s integrate all together. We must add values to insert.blade.php
name field:
price field:
button field:
And edit insert.php as follow.
So, we are connecting to the database, we are loading a new class called ProductDao and we are collecting the information of button, name and price. If the button is pressed, then we will call the function insert of ProductDao. If not, then we will do nothing.
So, let’s create the class ProductDao
ProductDao
Right now, this class does nothing but we will be able to run insert.php.
? vendor (the folders are close, we don’t delete the content)? view? dao . . . . . . .? ProductDao.php? compile? first_tut.php? insert.php? composer.json? composer.lock
If we call the page insert.php and we press the button, it must keeps the values of the textfields as follow.
ProductDao.php Mark-2:
And if we click on the button, it will not show any aditional but it will add a file inside the table. So let’s go back to Workbench, select the table, press on the “icon” indicated to see if the values are in the table.
Stage 6 List Form
It will be quick.
? vendor (the folders are close, we don’t delete the content)? view . . . . . . .? example . . . . . . .? product . . . . . . . . . . . . . .? insert.blade.php . . . . . . . . . . . . . .? list.blade.php? dao . . . . . . .? ProductDao.php? compile? first_tut.php? insert.php? list.php? composer.json? composer.lock
ProductDao.php Mark 3
ProductDao.php Mark-3 and final:
This class uses the library DaoOne. It is a small wrapper of MysqlI so it’s kind useful albeit basic.
$db->select(‘*’)->from(‘products’)->toList(); This commands generates a new query from products (select * from products) and returns (as array) the result. You could run too as $db->select(‘idproduct,name,price’)->from(‘products’)->toList();
$db->from(‘products’)->set($product)->insert(); This commands insert in the table products the values stored in $product. It works because the array product contains the same name of columns than the database. Otherwise, we should write it as follow $db->from(‘products’)->set([‘name’=>’xxx’,’price’=>4444])->insert();
list.blade.php (view)
We will copy the second page generates by Pingendo and we will replace the BODY of the TABLE as follow:
What is @foreach and {{}} ?. It is part of the specification of BladeOne. It’s a tag specifically of the template library. In this case, it uses the “language” Blade (same as Laravel) that it’s similar to php.
list.php (root folder)
It’s the same than the insert.php file. However, there is not input values. It also loads a list of products from the database. It uses the class ProductDao again.
Stage 6 Validation
It’s here where the things turn nasty.
What we should validate?
- Security (It is not part of the scope of this tutorial, yet!)
- What will happen if the database is down? or some operation fails?.
- What will happen if the user enters an incorrect name or price?
- What will happen if the user doesn’t enter any name or price?.
- What will happen if the operation to the database fails?.
- And the list could go.
In those cases, the system must fail gracefully (it must shows a error message instead of a PHP error)
We will add the next library for validation. eftec/validationone
So, let’s run the composer (shell) again
composer require eftec/validationone
Delete the vendor folder and let’s run the next command
composer update
? vendor (the folders are close, we don’t delete the content)? view . . . . . . .? example . . . . . . .? product . . . . . . . . . . . . . .? insert.blade.php . . . . . . . . . . . . . .? list.blade.php? dao? compile? first_tut.php? insert.php? list.php? composer.json? composer.lock
Validating list
list.php (root)
For this case, we are using the library ValidationOne. This library contains two modules:
- A validation Module ValidationOne
- A message List module MessageList. The Message List Module is inside validation and it’s accesible via field (messageList) but it’s also accesible via methods.
Both works in tandem.
In this page, validation is simple, if the operation fails, then we store a message (general is a name of a message container).
list.blade.php (view) After this code (the div “row” that contains the table)
We will add the next code (another row)
Here, we will use ValidationOne again. If there is an error then we will show the first error or warning contained in the container **general**
If the list fails, then it will show the next message:
Validating form
So, the code is quite long and it uses ValidationOne again.
First, ValidationOne keeps the error message, it does the basic validations and it also fetch the user input. How handy.
So instead of
we are using:
In this case, it sets the type of value, it sets a default value, it determines if the operationf ails then $button=0, and it fetchs from the post.
So, we do the same with frm_name and price
ValidationOne has a list of message called $val->messageList
This list contains the next containers of messages
- general (it just a name that we used)
- frm_button
- frm_name
- frm_price
So, it is possible to obtain the messages (such as error) for each one of the containers. Or we could obtain all the messages.
So, let’s modify the view for use the containers.
insert.blade.php (view)
If the operation fails, then it will show the next containers (text in red). It also shows a message if happens a “general” error.
Version
Some text is broken, some “folders” are broken. I am working on it.
1.0 2018–10–15 First version of the document. It has some typos there and here.Full code
Copyright
Jorge Castro Castillo Eftec MIT License. If you want to copy this document, then go ahead, but you should keep the copyright notice and the link.