Generic Admin Site in Php / Mysql - php

i am building a auto / generic client admin panel for Mysql Databases , it only takes a connection string and the system Dynamically creates all the The forms for all the tables with validation and Creates ALL CRUD operations for the tables in the database , i finished all that and did it OOP but the last thing to do is get the tables and Fields Relations Dynamically , so how can i implement that ?
Best Regards,

Look at the MySQL SHOW TABLES... and SHOW COLUMNS... statements.
If you're looking for foreign key constraints you can query INFORMATION_SCHEMA.TABLE_CONSTRAINTS and INFORMATION_SCHEMA.KEY_COLUMN_USAGE.

Both gonna help you out:
SELECT * FROM information_schema.KEY_COLUMN_USAGE WHERE table_schema='<database>' AND REFERENCED_COLUMN_NAME IS NOT NULL
Prints you all foreign keys of a specified database.
Can easily be used for any case of working with your foreign keys.
Might also be helpful:
Foreign key constraints missing from SHOW CREATE TABLE output

Related

CakePHP using a table to show relation between two tables

So I was building a cake project with a coworker the other day and he used a table in the database (users_credentials) to create a link between two constant tables (users and credentials.) When I tried to duplicate that result with a project I'm working on alone, it isn't working. Can anyone throw me a bone? I just need something to Google or a name or something.
Thanks
Justin
I think you want to connect a user to some credentials? What you can do is give each row an unique number (primary key) and combine those two keys in another table.
You could search google for "foreign keys and primary keys" I think, or search for an ERD (Entity-relationship diagram).
You will likely need to just do a join of the 3 tables. The CakePHP user guide offers some help on how to do that assuming you've got your application hooked up to the database correctly. It looks like Cake also does some of the heavy lifting for associating your Models with one another as well as documented here. I'm more familiar with CodeIgniter's syntax, but the basic idea is the same:
select something from users
join users_credentials on user id
join credentials on credential id

PHP My Admin Not Creating Relations

I am using xamp.
I created a DB using SQL Yog,
I opened my localhost/phpmyadmin/
then selected the newly created database.
I wanted to make relations among tables, for instance there are two tables,USER and USERSTATS, I want to create relation depending on USER_ID, which exists in both table.
I selected create relation option, selected reference key from USERS table, then click on STATS table and selected foreign key, i got a prompt "Create relation", I clicked OK.
Now it was to supposed to be creating relation, but it's not, just a small blank popup window opens in firefox, with link
localhost/phpmyadmin/pmd_general.php?db=MYDBNAME&server=1&token=d9d3ed2661d4cc1d0db47eca1ebee996
But it is not creating the relation.
Please assist me in resolving this issue
Have you created your tables with InnoDB ? InnoDB accepts creation of foreign keys
Did you go through the complete phpmyadmin installation steps? You have to create the phpmyadmin specific tables. Without them you will not be able to see relations or create them.
http://docs.phpmyadmin.net/en/latest/setup.html#phpmyadmin-configuration-storage
mysql doesn't support the foreign key relations, though it accepts that keyword. That's probably the reason phpMyAdmin doesn't allow this.
If you can use InnoDB engine for your table, foreign keys are supported.
From an answer from stackoverflow for why-my-table-doesnt-support-foreign-keys
ALTER TABLE tableName ENGINE = InnoDB;
you need to add an index to the field you want as foreign key. You can do it by going to the table and clicking "Index" or you can do it manually: "ALTER TABLE YourTable ADD INDEX ( YourField )"

Keep updated mysql data between multiple mysql tables

I have two tables in mysql. When I insert/delete values in the first table I want that the values get duplicated in table 2 to keep them "aligned".
table1:
id - username
1 - test_user
table2:
Same id as table1 and username as table1 (on insert/delete)
I want to keep the data between the tables aligned without doing multiple queries. I've read about triggers not sure if it's the correct road, i am a beninner.
I said two tables but i will need to do this in multiple tables.
You can use Mysql triggers. This way you can auto insert/update/delete datas from second table.
MySql Using Triggers
When you INSERT new records, given that you don't want to do two inserts for some reason, using a trigger to insert into the second table will work. For UPDATE and DELETE you might want to look at the CASCADE option with foreign keys. If all you are doing is keeping the data consistent between tables, that's exactly what cascade is for.
When you create table2 you just add a foreign key like this:
FOREIGN KEY (id, username)
REFERENCES table1(id, username) ON UPDATE CASCADE ON DELETE CASCADE
Then whenever you alter table1 the changes will automatically get pushed through to table2.
Couple prerequisites for this to work:
You have to use a storage engine that supports foreign keys, something like InnoDB and not MyISAM
You need to have an index on (id,username) in table1; the foriegn key needs to match a key in the parent table
You should read the doc page for foreign keys. There are a couple other ways you can tweak them, and you should figure out what works best for your purposes.
You can certainly put triggers on your table1 to make parallel changes to your other tables as your application changes table1.
See here for the documentation: http://dev.mysql.com/doc/refman/5.0/en/trigger-syntax.html
But, you should think over your design. It will take multiple queries to do your inserts and updates; they'll just be done "behind your back" on the server. They'll still take time. Triggers can really slow things down.
Also, triggers are a little bit fragile. If you add a column to a table, you'll have to rework your triggers. Triggers are generally a pain in the neck to keep in a source-control system and a huge pain in the neck to test, so using them will make your application more troublesome to maintain.
Could you think of another approach to handling this need for duplication? Could you, for example, use a view or a join to present the data you need to your application program without actually duplicating tables and the rows in them? If you figure out how to do that you'll be much happier in the long run.
CREATE VIEW table2 AS
SELECT *
FROM table1;
will produce a "fake" table2 with the contents of table1.
Or if you're hoping to view only the test users in a second table, a view can do that for you too, for example:
CREATE VIEW table3 AS
SELECT *
FROM table1
WHERE usertype = 'test_user' ;
If you're using duplicate tables for "backup," that's a bad way to make sure your information is safe. Instead, you need to back up your MySQL server instance.
Formal relational database design principles teach us to duplicating data, but instead use view and joins to structure the data the way applications need to see it.

PHP MySQL query against changing database

I am developing a PHP web based data entry tool with MySQL as the database. However the database will undoubtedly change whilst the data entry is going on (there is a lot of it to be done so we have started it so that it runs in parallel to the other development).
I have constructed the SQL queries so that the php can automatically:
Determine what tables are in the database
List tables with a certain prefix so that only ones that data entry should use are listed
However, what I cant figure out (despite checking php, sql and mysql manuals and tutorials) is how to automatically pull tables that are connected by foreign key, so that data entry have a list of items to choose from for the given table. So in short, how do I - using php - determine:
Any foreign keys for the given table
The table name that the foreign key points to
WITHOUT hard-coding any table names into the SQL queries?
A quick way to list your Foreign Key references using the KEY_COLUMN_USAGE view:
SELECT CONCAT( table_name, '.',
column_name, ' -> ',
referenced_table_name, '.',
referenced_column_name ) AS list_of_fks
FROM information_schema.KEY_COLUMN_USAGE
WHERE REFERENCED_TABLE_SCHEMA = (your schema name here)
AND REFERENCED_TABLE_NAME is not null
ORDER BY TABLE_NAME, COLUMN_NAME;
This query does assume that the constraints and all referenced and referencing tables are in the same schema.
For InnoDB tables, using the Comment field of SHOW TABLE STATUS is useful for extracting foreign key information for older versions of MySQL.
I am unaware of any other way than the above 2 methods.
Happy coding!

Merge several mySQL databases with equivalent structure

I would like write a php script that merges several databases, and I would like to be sure of how to go around it before I start anything.
I have 4 databases which have the same structure and almost same data. I want to merge them without any duplicate entry while preserving (or re-linking) the foreign keys.
For example there is a db1.product table which is almost the same as db2.products so I think I would have to use LIKE comparison on name and description columns to be sure that I only insert new rows. But then, when merging the orders table I have to make sure that the productID still indicates the right product.
So I thought of 2 solutions :
Either I use for each table insert into db1.x as select * from db2.x and then make new links and check for duplicate using triggers.
Either I delete duplicate entries and update new foreign keys (after having dropped constraints) and then insert row into the main database.
Just heard of MySQL Data Compare and Toad for mySQL, could they help me to merge tables ?
Could someone indicate to me what should be the right solution ?
sorry for my english and thank you !
First thing is how are you determining whether products are the same? You mentioned LIKE comparison on name and description. You need to establish a rule what says that product is one and the same in your db1, db2 and so on.
However, let's assume that product's name and description are the attributes that define it.
ALTER TABLE products ADD UNIQUE('name', 'description');
Run this on all of your databases.
After you've done that, select one of the databases you wish to import into and run the following query:
INSERT IGNORE INTO db1.products SELECT * FROM db2.products;
Repeat for the remaining databases.
Naturally, this all fails if you can't determine how you're going to compare the products.
Note: never use reserved words for your column names such as word "name".
Firstly, good luck with this - sounds like a tricky job.
Secondly, I wouldn't do this with PHP - I'd write SQL to do the work, assuming this is a one-off migration task and not a recurring task.
As an approach, I would do the following.
Create a database with the schema you want - it sounds like each of your 4 databases have small variations in the schema. Just create the schema for now, don't worry about the data.
Create a "working" database, with the same schema, but with columns for "old" primary keys. For instance:
table ORDER
order_id int primary key auto increment
old_order_id int not null
...other columns...
table ORDER_LINE
order_line_id int primary key auto increment
old_order_line_id int not null
order_id int foreign key
...other columns...
Table by table, Insert into your working database from your first source database. Let the primary keys auto_increment, but put the original primary key into the "old_" column.
For instance:
insert into workingdb.orders
select null, order_id, ....other columns...
from db1.orders
Where you have a foreign key, populate it by finding the record in the old_ column.
For instance:
insert into workingdb.order_line
select null, ol.order_line_id, o.order_id
from db1.order_line ol,
workingdb.order
where ol.order_id = o.old_order_id
Rinse and repeat for the other databases.
Finally, copy the data from your working database into the "proper" database. This is optional - it may help to retain the old IDs for lookups etc.

Categories