Skip to content

Instantly share code, notes, and snippets.

@edgvi10
Created January 22, 2021 23:54
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 edgvi10/ed7176562981614cc4ce1476ab3a807f to your computer and use it in GitHub Desktop.
Save edgvi10/ed7176562981614cc4ce1476ab3a807f to your computer and use it in GitHub Desktop.
Funções PHP para converter Arrays em SQL
<?php
function parseValue($value)
{
$functions = ["UUID()", "NOW()", "NULL"];
$useapostrofe = true;
if ($useapostrofe) $useapostrofe = (array_search($value, $functions) === false) ? true : false;
if ($useapostrofe) $useapostrofe = (hexdec(intval($value)) == hexdec($value)) ? false : true;
if ($useapostrofe) $useapostrofe = (hexdec(floatval($value)) == hexdec($value)) ? false : true;
$value = $useapostrofe ? "'{$value}'" : $value;
return $value;
}
function sqlSelect(string $table, array $options, $debug = false)
{
$cols = (isset($options["cols"]) && !empty($options["cols"])) ? implode(", ", $options["cols"]) : "*";
$join = (isset($options["join"]) && !empty($options["join"])) ? implode(" ", $options["join"]) : NULL;
$where = (isset($options["where"]) && !empty($options["where"])) ? " WHERE " . implode(" AND ", $options["where"]) : NULL;
return ($debug) ? [$table, $options] : "SELECT {$cols} FROM {$table}{$join}{$where}";
}
function sqlInsert(string $table, array $data, $debug = false)
{
$is_assoc = array_keys($data) !== range(0, count($data) - 1);
$cols = [];
$values = [];
if ($is_assoc) :
foreach ($data as $field => $value) :
$cols[] = $field;
$values[] = parseValue($value);
endforeach;
else :
foreach ($data as $row) :
foreach ($row as $key => $value) :
$value = parseValue($value);
$cols[] = $key;
$value_row[] = $value;
endforeach;
$multiple[] = implode(", ", $value_row);
endforeach;
$values = implode("), (", $multiple);
endif;
$cols = implode("`, `", $cols);
$values = implode(", ", $values);
return ($debug) ? [$table, $data] : "INSERT INTO {$table} (`{$cols}`) VALUES ({$values})";
}
function sqlUpdate(string $table, array $data, array $where, $debug = false)
{
$values = (array) $data;
foreach ($values as $field => $value) :
$val = parseValue($value);
$fields[] = "`{$field}` = {$val}";
endforeach;
$fields = " SET " . implode(", ", $fields);
$where = (isset($where) && !empty($where)) ? " WHERE " . implode(" AND ", $where) : NULL;
return ($debug) ? [$table, $data, $where] : "UPDATE {$table}{$fields}{$where}";
}
function sqlDelete(string $table, array $where, $debug = false)
{
$where = (isset($where) && !empty($where)) ? " WHERE " . implode(" AND ", $where) : NULL;
return ($debug) ? [$table, $where] : "DELETE {$table}{$where}";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment