D
D
Dmitry2015-02-04 15:22:24
PHP
Dmitry, 2015-02-04 15:22:24

How to create generic Create CRUD operation in php for different tables?

I'll try to explain what I mean.
I am developing a class for CRUD operations for my project.
There is a function for Update. It is quite simple, I pass it an array with pairs: key-value. The key is equal to the name of the corresponding column in the database. I just go through all these pairs in a loop and update the fields in the database that are in this array. The sql query is formed like UPDATE table SET f1 = v1, f2=v2 ... etc.
Those. the values ​​after "SET" are actually the pairs from the array: key-value. Accordingly, this function can be applied to absolutely any table, if you follow the rule that data is transferred to it where the key in the array would correspond to the name of this field in the database.
But what about the add operation? After all, the INSERT query has such a syntax that it must necessarily list all the fields that are in the table, and even in the right order. It turns out that this function cannot be passed an arbitrary set of data, which will be added to the database?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
F
FanatPHP, 2015-02-04
@battrack

it must contain all the fields

Who said?
Who said?
unnecessary.
It makes no sense to fence the whole class just for the sake of being able to add data to update from an array. By tying himself hand and foot for it.
D after all works for you only on primary key - is true? And on the composite already in any way.
U at you updates only values. But what if the request needs to use a function? Like NOW(), INET_ATON()?
With you can only stupidly insert the list. But in real life, this query has a much richer syntax . I generally keep quiet
about R. You have hell, trash and waste there.
And this despite the fact that you just need to learn how to add a couple of non-standard data types to the query.
include 'safemysql.class.php';
$db    = new SafeMysql();
$table = "test"; 

if (isset($_POST['delete'])) {
    $db->query("DELETE FROM ?n WHERE id=?i", $table, $_POST['id']);
} elseif ($_POST['id']) { 
    $db->query("UPDATE ?n SET ?u WHERE id=?i",$table, $data, $_POST['id']);
} else { 
    $db->query("INSERT INTO ?n SET ?u", $table, $data);
}

- here's the whole CRUD in 5 lines

V
Viktor Vsk, 2015-02-04
@viktorvsk

php.net/manual/en/book.pdo.php
And see what Database Migrations are

D
Dmitry Bay, 2015-02-04
@kawabanga

Make a request to the database dev.mysql.com/doc/refman/5.0/en/show-columns.html
and then use the received data to correctly compose the sql insert query.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question