Easiest way to create a CRUD with PHP - php

I'm new to PHP (used to Python) and I've been instructed to create something that will allow users to CRUD entries. I was originally going to use a textarea field and sort by which numbered row they were, but I realized that if a user deleted a row, that it would screw up all the UIDs for the whole system.
So now here I am, several hours into the project and trying to figure out what's the best way to create something which A) allows multiple rows of data B) allows this information to be deleted or updated C) allows additional rows to be added D) shows all the rows available (this can be scrollable, so that it all doesn't display at once)
Database is MySQL
Are any of these easy to integrate? I don't know quite how much access I have to the server that this is running on.

It's a bit overkill, but you can very quickly get a basic and flexible CRUD up and running by installing CodeIgniter and then GroceryCRUD.

Some PHP frameworks come with built-in CRUD, but since OP didn't ask for any specific framework, then my answer recommends a framework-agnostic CRUD.
Agile UI is an open-source PHP UI component library containing CRUD, Grid, Form, Menu and many other visual elements you can use out-of-the box.
15 lines of PHP, (no HTML and no boilerplate code) is enough to build this UI:
Here is full code:
require 'vendor/autoload.php';
$app = new \atk4\ui\App('My App');
$app->initLayout(new \atk4\ui\Layout\Admin());
$db = \atk4\data\Persistence::connect($DSN);
class User extends \atk4\data\Model {
public $table = 'user';
function init() {
parent::init();
$this->addField('name');
$this->addField('email', ['required'=>true]);
$this->addField('password', ['type'=>'password']);
}
}
$app->layout->add(new \atk4\ui\CRUD())
->setModel(new User($db));
You'll need to also run: composer require atk4/ui but that's it.

Consider looking at a framework that comes with prototyping or scaffolding support like CakePHP. Besides PHPMyAdmin, that's probably the fastest way of getting CRUD functionality to work with an existing datastore.

I recommend using the yiiframework. It design is pythonesque like. The Gii generator that comes with Yii will read you DB tables and create all the necessary CRUD code for some simple editing.
http://www.yiiframework.com/

I'm looking for a drop-in admin like this too, here's one I found so far:
http://ajaxcrud.com/

Related

Creating a PHP wrapper for MongoDB and MysqlDB X DevApi

I am working on a project that use MongoDB to house transactional data with MySQL housing all other data. For various reasons, we are looking at the possibility of moving from MongoDB to the MySQL xDevApi with the 8.0 version. In preparation for this possibility as well as to ease the learning curve as well as other database considerations, I am looking at creating a wrapper that will allow us to switch the database backend without having to update all the places in the code that interfaces with MongoDB.
I have an outline of one already, but am not sure it is the best way to do it. I think it is a decent start, I am just not certain of the file/folder structure.
The current file/folder structure is as follows:
\DocumentStore
abstract class DocumentStoreQueryBuilder
interface IDocumentStore
interface IDocumentStoreConnection
\DocumentStore\Mongo
class Connection implements IDocumentStoreConnection
class Query implements IDocumentStore
class QueryBuilder extends BuilderAlias
My thought is to use language similar to a relational database in order to help with the initial learning curve of those coming from a RDB background (the majority of those that will be coming onto the project).
I am sure that there is a better way to organize things, but to be honest, I am not too terribly familiar with Document Storage generally.
This is code that works with what I have so far.
In the connection file that is called from all files that need the connection.
$mgdbdoc = new DocumentStore\Mongo\Connection();
$connectionString = $mgdbdoc->buildConnectionString($settings);
$mgdbdoc->connect($connectionString);
$collection = new DocumentStore\Mongo\Query($mgdbdoc);
Defines the collection for action on. This could, theretically, be saved to a unique class name for each collection if necessary.
$collection->setCollection('transactions');
To be called whenever necessary.
$result = $collection->insert($document);
$result = $collection->filter($filter)->limit(2)->descending('_id')->select();
I haven't put in the update and remove functionality yet, and the and/or functionality is proving difficult, but I can get that.
My question is for any advice regarding this project. Any thoughts on proceeding forward? I haven't been able to locate a wrapper for multiple NoSQL databases like there is for PDO. I would appreciate any thoughts or advice.

Creating HTML form from mysql table like gii of yii framework

Is there any application which automatically creates html form from given mysql table like the one gii does of yii framework.
Or, is there any way, i can use gii for my own purpose without using using yii framework.
I don't want complete CRUD feature in it, Even if it's just list out my data with pagination, that will do my work.
Thanks
This URL will help you!
http://developer.ifreelance.asia
I found this on facebook page. I use it myself, and this is real handy.
Well, if you really think about it, phpmyadmin creates forms using the database structure. The ultimate CMS is phpmyadmin :).
Anyway to answer your question. You can always create your own Gii template that creates it as you need it. I have custom models and custom forms that get created. There is nothing that prevents me from rolling out anything I actually want with Gii.
The only 1 problem that I can think about is that you create the model and then, based on the Yii model you create the CRUD. If you really want to use Gii you should create your own model however you want, create a Yii model too (quite easy to create both, one after the other as you can use 2 different templates) then create the CRUD based on the Yii model, but the CRUD you need.
Probably you can do it directly but I have never tried it.
Point is, you can use Gii to create a model for any ORM. It just creates a text file and you can modify it. The CRUD might require 2 steps but you should also be able to create the CRUN as you want.

CodeIgniter CRUD structure

I'm using Codeigniter to flesh out a pretty large project (especially for a n00b). One issue I'm having is how to organise my files and methods. I've broken my project down into features - the app is a task management software so already we have basic features such as "Task", "Project", "User" etc.
The way I intend to do this is by creating controllers for each and then following CRUD methodology in each. So for example in Task we would have the following methods:
create()
read()
update()
delete()
This makes sense in my head. Now in terms of Views, should I have multiple views, or should I combine create and update into the same form? Also, where does non-View functionality go, such as setting cookies etc?
This is quite a specific question but if anybody has any more holistic guides on general structure convention for CodeIgniter projects I'd be very grateful.
I'd say you got it right. This is what I do.
I tend to use the same view for create and update, keep it DRY (don't repeat yourself) if you can.
Non-view related stuff that does not handle anything business-related goes in what I call helper-classes. If it's business related, I put all the logic into services, so I can unit-test them without being dependant of any framework (not sure how new you are at this, but oh well :) ).
You can also use Grocery Crud, a library that provides out of the box CRUD functionality for codeigniter.
It handles pretty good 1->n and n->n relationships so its convenient for small projects.
I don't know if you are familiar with it. If not give it a try. It will save you tons of time and effort.
My controller consists of these methods, which follows REST API guidelines:
read -> get all records.
find -> find record by primary key/id.
create -> show the form view.
store -> insert data from the form into the database.
edit -> show the form view, populated with current records' data.
update -> update data from the form into the database.
delete -> delete data from the database.
This is called Resourceful Controllers.
Yes, you can combine create and edit in same form. However, there are cases those require you to use different create and edit form. In that case, just make 2 separate forms.
And... like #Theodore suggested, GroceryCRUD is worth a try if you don't need too many customizations.

PHP authentication library, how to build and configure it?

The Title may not be as clear but Il explain what's my problem.
Im building PHP MVC framework for my project. I know there are awsome PHP frameworks, but I like to code and Im doing this to learn more about PHP and MVC and other OOP patterns.
It works great, at least components I built so far.
I use PHP 5.3 and namespaces, so I can require/load classes based on their namespaces/names.
I built SPR-0 class loader class and it enables me to use other libraries that use SPR-0 "standard"/convention like Doctrine or Symfony2 components inside my framework. And all functionality of the framework itself, i call it Core, is writen as a component. So i have \Core\Controller\Controller() class or \Core\Router\Dispatcher() class or \Filesystem\FileManager() class. So I use them where I need them. And Core components enables me to add routes, detect them, call aproppriate controller/action etc... to build an MVC basicly.
And now I need Authentication modul to check if user is loged in on protected pages.
How do I setup that? The bigest problem is how do I tell Authentication Module what tables to use? Where to find usernames and where to find passwords? How do I configure Authentication module, so it knows where to look for username and password?
I could setup users table in database and never change it, and then instruct Authentication where to find stuff he needs. But what if on next project I would like to use different database design, and i would like to use email row instead of username?
Hope you understand whats bothering me...
The short question is how to setup Authentication class/module so you can configure it later to use other rows to fetch data from, and how flexible can that class can be, as far as configuration goes? Should I map some where in configuration that variable username maps to table users row username, so i can change it latter to email? How do you build flexible and configurable Auth library?
The question is long, so thanks for reading...
If I understand you correctly, you want to be able to choose different DB tables for Auth depending upon what project you're working in...
Well why don't you create a config file that gets 'read' by the framework first thing?
That's what other frameworks do I think. You provide host,dbname,user and so on... In your case you'd, in addition to that, write in the config what tables and fields to use for authentication/auhorization?

Entity Framwework-like ORM NOT for .NET

What I really like about Entity framework is its drag and drop way of making up the whole model layer of your application. You select the tables, it joins them and you're done. If you update the database scheda, right click -> update and you're done again.
This seems to me miles ahead the competiting ORMs, like the mess of XML (n)Hibernate requires or the hard-to-update Django Models.
Without concentrating on the fact that maybe sometimes more control over the mapping process may be good, are there similar one-click (or one-command) solutions for other (mainly open source like python or php) programming languages or frameworks?
Thanks
SQLAlchemy database reflection gets you half way there. You'll still have to declare your classes and relations between them. Actually you could easily autogenerate the classes too, but you'll still need to name the relations somehow so you might as well declare the classes manually.
The code to setup your database would look something like this:
from sqlalchemy import create_engine, MetaData
from sqlalchemy.ext.declarative import declarative_base
metadata = MetaData(create_engine(database_url), reflect=True)
Base = declarative_base(metadata)
class Order(Base):
__table__ = metadata.tables['orders']
class OrderLine(Base):
__table__ = metadata.tables['orderlines']
order = relation(Order, backref='lines')
In production code, you'd probably want to cache the reflected database metadata somehow. Like for instance pickle it to a file:
from cPickle import dump, load
import os
if os.path.exists('metadata.cache'):
metadata = load(open('metadata.cache'))
metadata.bind = create_engine(database_url)
else:
metadata = MetaData(create_engine(database_url), reflect=True)
dump(metadata, open('metadata.cache', 'w'))
I do not like “drag and drop” create of data access code.
At first sight it seems easy, but then you make a change to the database and have to update the data access code. This is where it becomes hard, as you often have to redo what you have done before, or hand edit the code the drag/drop designer created. Often when you make a change to one field mapping with a drag/drop designer, the output file has unrelated lines changes, so you can not use your source code control system to confirm you have make the intended change (and not change anything else).
However having to create/edit xml configuring files is not nice every time you refractor your code or change your database schema you have to update the mapping file. It is also very hard to get started with mapping files and tracking down what looks like simple problem can take ages.
There are two other options:
Use a code generator like CodeSmith that comes with templates for many ORM systems. When (not if) you need to customize the output you can edit the template, but the simple case are taken care of for you. That ways you just rerun the code generator every time you change the database schema and get a repeatable result.
And/or use fluent interface (e.g Fluent NHibernate) to configure your ORM system, this avoids the need to the Xml config file and in most cases you can use naming conventions to link fields to columns etc. This will be harder to start with then a drag/drop designer but will pay of in the long term if you do match refactoring of the code or database.
Another option is to use a model that you generate both your database and code from. The “model” is your source code and is kept under version control. This is called “Model Driven Development” and can be great if you have lots of classes that have simpler patterns, as you only need to create the template for each pattern once.
I have heard iBattis is good. A few companies fall back to iBattis when their programmer teams are not capable of understanding Hibernate (time issue).
Personally, I still like Linq2Sql. Yes, the first time someone needs to delete and redrag over a table seems like too much work, but it really is not. And the time that it doesn't update your class code when you save is really a pain, but you simply control-a your tables and drag them over again. Total remakes are very quick and painless. The classes it creates are extremely simple. You can even create multiple table entities if you like with SPs for CRUD.
Linking SPs to CRUD is similar to EF: You simply setup your SP with the same parameters as your table, then drag it over your table, and poof, it matches the data types.
A lot of people go out of their way to take IQueryable away from the repository, but you can limit what you link in linq2Sql, so IQueryable is not too bad.
Come to think of it, I wonder if there is a way to restrict the relations (and foreign keys).

Categories