0

This question is kind of two-fold - a) am I approaching it in a valid way, and b) how would it be done in php.

I have hundreds of php forms in a legacy site, going forward I am trying to clean up the code and modularise it more.

So I am creating a database functions file, in which I would like to use a general INSERT function. Now, each form will have a totally different table, therefore different fields to insert.

I cannot find the best way to write this function - I was thinking something like this:

function insert_form_data($table, $arr_fields, $arr_values)

In this way, I am unsure how to structure the myqli query function to use the fields and values array when they are unknown.

So is this a valid way to do it, if so, please help with the syntax. Or should I spend the extra time now refactoring everything into using the mvc structure, in which case each table/form would be a 'model' etc..

thx

2 Answers 2

3

A very simple example for what you want is

public function insert_form_data($table, $arr_fields, $arr_values)
{

    $sql = 'INSERT INTO '.$table.' ('.implode(", ", $arr_fields).') VALUES ('.implode(", ",  $arr_values).')';

    return mysql_query($sql);

}

you can change it accordingly if you are using PDO connection. Better if you make complete class which check connection on constructor and perform all insert update delete function.

Sign up to request clarification or add additional context in comments.

3 Comments

Maybe don't show the mysql_query() function. You'll get ridiculed very quickly because it's a deprecated library. (PDO or mysqli are the way to go here)
I just want to show how things can be done and this is just for demonstration. that's why I mentioned to use PDO
In a production environment, it is very important that $table, $arr_fields, and $arr_values be sanitized/error-checked before the query is generated and run. If these values came from user input then the example implementation would be vulnerable to a SQL injection attack.
0

Method Implementation

public function addData($_tableName, $_dataString){
    $qr_string = 'INSERT INTO `'.$_tableName.'` SET '.$_dataString;
    $this->_message = ($this->res = $this->mysqli->query($qr_string)) ? 'Success' : $this->mysqli->error ;
    return $this->_message;
}

Hope This Helps

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.