* Add DB Entry * @param string table * @param array fields * [ array('name' => $name, 'value' => $value) ] */
($table, array $fields)
| 428 | * [ array('name' => $name, 'value' => $value) ] |
| 429 | */ |
| 430 | public static function add_db_entry($table, array $fields) |
| 431 | { |
| 432 | |
| 433 | // We're going to use the field count a few times, |
| 434 | // so let's create the variable first. |
| 435 | $field_count = count($fields); |
| 436 | |
| 437 | // Let's reformat fields into something easier for |
| 438 | // MySQL to deal with. |
| 439 | $field_names = ''; |
| 440 | $field_values = array(); |
| 441 | if(!empty($fields)){ |
| 442 | $counter = 0; |
| 443 | foreach($fields as $field){ |
| 444 | $counter++; |
| 445 | $field_names.= '`'.$field['name'].'`'; |
| 446 | if($counter !== $field_count) |
| 447 | $field_names.= ', '; |
| 448 | array_push($field_values, $field['value']); |
| 449 | } |
| 450 | } |
| 451 | |
| 452 | // Prepare the SQL. |
| 453 | $sql = 'INSERT INTO `'.$table.'` ('.$field_names.') '; |
| 454 | $sql.= 'VALUES ('.str_repeat('?, ', $field_count).')'; |
| 455 | $sql = str_replace(', )', ')', $sql); |
| 456 | |
| 457 | // Query |
| 458 | $result = self::query($sql, $field_values, false); |
| 459 | |
| 460 | // Fallback |
| 461 | if(!$result) |
| 462 | throw new Exception('Cannot add DB entry'); |
| 463 | |
| 464 | // Complete Query |
| 465 | return $result; |
| 466 | |
| 467 | } |
| 468 | |
| 469 | /** |
| 470 | * Add DB Rows |
no test coverage detected