Im gonna show you a simple function in php that will help you to generate the easiest insert mysql query (yet another...).
I use it in a personal web application, someone could find it useful too. It's just an alpha definition, but i really doubt to bring new modifications.
Context:
This function have been called in a asynchronous way from javascript (by XHR), so the parameters comes from $_GET array.
The function accept these parameters as input:
- $table: name of the table the query concern;
- $get_unset: ignored $_GET array's indexes that don't need to build the query;
- $auto_id: this boolean flag is set to true if in that table exist an index called id which is autoincrement
It is clear the follow adaptations should be take into consideration: add an array parameter as a substitute of $_GET array, so $unset_get could be remove from the parameters list.
function generate_query($table, $get_unset = null, $auto_id = true) {
$field = "";
$value = "";
foreach($get_unset as $gu) unset($_GET[$gu]);
$query = "INSERT INTO $table(";
foreach($_GET as $k => $v) {
$field .= "$k, ";
$value .= "'$v', ";
}
if($auto_id) $query .= "id, ";
$query .= substr($field, 0, -1).") VALUES(";
if($auto_id) $query.="null, ";
$query .= substr($value, 0, -1).")";
return $query;
}