Creating an inline editable grid with PHP and MySql
Example PHP Inline Editable Grid with MySQL
It is an example of an inline editable grid, using PHP and MySQL where you can display, edit, delete and add new elements to and from a table. Also, one of the fields is selectable (combobox).
This example uses jQuery, Ajax and a library called Gijgo
1- Configuring Composer.
For this exercise, we need composer installed and running (also PHP and MySQL)
Initialize composer as follow.
composer init
Welcome to the Composer config generatorThis command will guide you through creating your composer.json config.Package name (<vendor>/<name>) [jorge/example-php-editablegrid]: eftec/example-php-editablegrid
Description []: It is an tutorial to create an editable grid with php and mysql
Minimum Stability []:
Package Type (e.g. library, project, metapackage, composer-plugin) []: project
License []: MITDefine your dependencies.Would you like to define your dependencies (require) interactively [yes]?
Search for a package: eftec/bladeone
Enter the version constraint to require (or leave blank to use the latest version):
Using version ^3.43 for eftec/bladeone
Search for a package: eftec/pdoone
Enter the version constraint to require (or leave blank to use the latest version):
Using version ^1.37 for eftec/pdoone
Search for a package:
Would you like to define your dev dependencies (require-dev) interactively [yes]? noDo you confirm generation [yes]?
Would you like the vendor directory added to your .gitignore [yes]?
Would you like to install dependencies now [yes]?
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 2 installs, 0 updates, 0 removals - Installing eftec/bladeone (3.43): Loading from cache
- Installing eftec/pdoone (1.37): Loading from cache
eftec/bladeone suggests installing eftec/bladeonehtml (Extension to create forms)
eftec/pdoone suggests installing eftec/validationone (For keeping and storing the messages)
Writing lock file
Generating autoload files
We will also add the next libraries eftec/bladeone and eftec/pdoone. (template and database)
2 Creating tables
We need to create two tables on MySQL. The case of the column matters.
Country
Via code
CREATE TABLE country (
`IdCounty` INT NOT NULL AUTO_INCREMENT,
`Name` VARCHAR(45) NULL,
PRIMARY KEY (`IdCounty`));
Or using an IDE
Table players
Using script
CREATE TABLE `players` (
`ID` INT NOT NULL AUTO_INCREMENT,
`Name` VARCHAR(50) NULL,
`IdCounty` INT NULL,
`IsActive` INT NULL,
PRIMARY KEY (`ID`),
INDEX `players_fk_idx` (`IdCounty` ASC) VISIBLE,
CONSTRAINT `players_fk`
FOREIGN KEY (`IdCounty`)
REFERENCES `country` (`IdCounty`)
ON DELETE NO ACTION
ON UPDATE NO ACTION);
And a foreign key (table players)
3 Adding Data to the table
Data to Country
INSERT INTO `country` (`IdCounty`, `Name`) VALUES ('1', 'USA');
INSERT INTO `country` (`IdCounty`, `Name`) VALUES ('2', 'Canada');
INSERT INTO `country` (`IdCounty`, `Name`) VALUES ('3', 'Mexico');
INSERT INTO `country` (`IdCounty`, `Name`) VALUES ('4', 'Portugal');
Data to Players
INSERT INTO `players` (`ID`, `Name`, `IdCounty`, `IsActive`) VALUES ('1', 'Bryce Harper', '1', '1');
INSERT INTO `players` (`ID`, `Name`, `IdCounty`, `IsActive`) VALUES ('2', 'Manny Machado', '2', '0');
INSERT INTO `players` (`ID`, `Name`, `IdCounty`, `IsActive`) VALUES ('3', 'Carlos Correa', '1', '1');
INSERT INTO `players` (`ID`, `Name`, `IdCounty`, `IsActive`) VALUES ('4', 'Francisco Lindor,', '3', '1');
4 Creating the Repository Layer
The repository layer is classes that have functions to access the database, for example, insert,update, etc.
The library PdoOne allows to create the repository layer using the database.
Let’s create this PHP file (in the root of the project)
📄/genrepo.php
<?phpuse eftec\PdoOne;include "vendor/autoload.php";$pdo=new PdoOne('mysql','127.0.0.1','root','abc.123','example_editable_grid');
$pdo->logLevel=3;
$pdo->render();
where 127.0.0.1 is the server, root = user, abc.123 = password and example_editable_grid our base.
loglevel=3 is if something goes south then it will show the error.
And renders shows the next screen: (open the page to show this page)
Add the next information. Where it says “input”, select the name of the table to generate (country or players)
For output, selects the option “classcode”. It will generate our class.
Press generate and copy the result (is generated in log text area)
It will generate the next code
<?php
/** @noinspection PhpUnused */use eftec\PdoOne;
use eftec\_BasePdoOneRepo;
class CountryRepo extends _BasePdoOneRepo
{
const TABLE = 'country';
// .... more code}
Copy this code and save in a folder (in my case I will use the folder repo)
Repeats the same procedure with all the tables.
📄 repo/CountryRepo.php
📄 repo/PlayersRepo.php
5 Views
In the folder views, create the next file 📄 views/table.blade.php
It also uses a web service called 📁 ws/server.php that it does not exists yet but we will create it later.
📄 views/table.blade.php
6 Our webpage
It is our code page. It doesn’t do much (yet) but later you could add some code. This code will call our view (created in the previous step)
📄 /table.php
<?phpuse eftec\bladeone\BladeOne;include "vendor/autoload.php";$blade=new BladeOne();
echo $blade->run('table',[]);
7 And let’s run
Ok, it is a start but it misses the web services mentioned in the step 5.
8 Creating web service.
Create a new PHP file called 📄 ws/server.php with the next content.
📄 ws/server.php
What it does? I will explain:
8.1 Connecting to the database
The first part of the code, connects to the database. In error, it dumps the error. You should change the information of the database such as user, password, etc.
$pdoOne=new PdoOne('mysql','127.0.0.1','root','abc.123','example_editable_grid');
$pdoOne->logLevel=3;
try {
$pdoOne->connect();
} catch (Exception $e) {
var_dump($e->getMessage());
die(1);
}
$action=@$_GET['action'];
It also reads the argument of the URL called action, i.e. ws/server.php?action=somevalue
8.2 Inserting
For inserting, we create an empty array and we use the class PlayersRepo (created automatically)
$record=PlayersRepo::factoryNull();
PlayersRepo::insert($record);
8.3 Listing
Listing the countries. We use the class CountryRepo. We could also sort, paging and filtering.
$result = CountryRepo::toList(); // select * from country
Listing the players. We need a custom query so we create it directly (without the Repository class). It is because we need all the columns of players but also the name of the country.
$r['records'] = $pdoOne->select('ID,Players.Name,Country.Name as CountryName,IsActive')->from('Players')
->left('Country on Players.IdCounty=Country.IdCounty')->toList();
8.4 Update and delete
We update with an array with all the columns. For delete, we only need the primary key.
PlayersRepo::update($record);PlayersRepo::deleteById($id);
9 Let’s run
Execute the same page than step 7 and it is the final result. If something fails, then you could check the error with your browser (KEY F12)
10 Final step
:-)
You can check the code on.