Skip to content

Instantly share code, notes, and snippets.

Created October 20, 2014 00:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/cb5244c70ac7c2d6099c to your computer and use it in GitHub Desktop.
Save anonymous/cb5244c70ac7c2d6099c to your computer and use it in GitHub Desktop.
Some PHP I wrote for an invoice generator. /r/badcode
function mysqliInsert($table, $fields, $optional){
$mysqli = new mysqli("localhost", "dbUser", "dbPass", "dbName"); //connect to database
$arrayLen = count($fields);
$query = "INSERT INTO $table("; //Generate Insert Statement
$i = 1;
foreach ($fields as $field => $value) { //Fields here
$query .= $field;
if($i < $arrayLen){ //To remove trailing comma
$query .= ", ";
};
$i++;
};
$query .= ") VALUES ("; // Values go here
$i = 1;
foreach ($fields as $field => $value) {
$query .= "'" . $value . "'";
if($i < $arrayLen){
$query .= ", ";
}
$i++;
}
$query .= ");";
if($result = mysqli_query($mysqli, $query)){
if(array_key_exists('extra', $optional)){
return mysqli_insert_id($mysqli);
};
};
};
$i = 0;
foreach($_POST['service'] as $key => $value){
if($value !== ''){
$table = 'billedServices';
$fields = [
'description' => $value,
'cost' => $_POST['cost'][$i],
'invoiceNo' => $lastId
];
$optional = [];
mysqliInsert($table, $fields, $optional);
};
$i++;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment