<?php
ini_set("display_errors", 1);
error_reporting(E_ALL);

include("connect.php");
function insertData($table, $data){
  //traer coneccion
  global $connection;
  
  //checar que valores necesitan comillas y cuales no...
  $hasQuotes = [];
  $query = "SHOW COLUMNS FROM `$table`";
  $result = mysqli_query($connection,$query);
  while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
    //si es un numero o buleano no lleva, si es otra cosa, si.
    if(stripos($row['Type'], "int") === 0 || stripos($row['Type'], "double") === 0 || stripos($row['Type'], "tinyint") === 0 || stripos($row['Type'], "numeric") === 0 || stripos($row['Type'], "double") === 0 || stripos($row['Type'], "decimal") === 0 || stripos($row['Type'], "float") === 0 || stripos($row['Type'], "bigint") === 0 || stripos($row['Type'], "real") === 0 || stripos($row['Type'], "bool") === 0){
      $hasQuotes[$row['Field']] = false;
    }else{
      $hasQuotes[$row['Field']] = true;
    }
  }
  //comenzar el statement...
  $query = "INSERT INTO `$table` (`" . implode('`,`', array_keys($data)) . "`) VALUES (";
  $saveQuery = [];
  //iterar por cada columna de la tabla
  foreach($hasQuotes as $fieldName => $quotes){
    //si no le asiganste valor en el array, lo excluye con este if...
    if(!is_null($data[$fieldName])){
      //si hay valor, aqui se le añaden las comillas si es necesario.
       $returnValue = ($hasQuotes[$fieldName])?"'{$data[$fieldName]}'":"{$data[$fieldName]}";
      $saveQuery[] = " $returnValue ";
		}
  }
  //aqui se le añaden los valores al query...
  $query .= implode(", ", $saveQuery) . ")";
  
  if($result = mysqli_query($connection, $query)){
    return $result;
  }else{
    echo mysqli_error($connection);
  }
  
}
//usage:
insertData("TABLE", array( "AccountNumber" => "123456", "Qty" => "10", "OrderNumber" => "W234S9-03", "SoldPrice" => "19.95" ) );
 ?>

