Skip to content

Instantly share code, notes, and snippets.

@julp
Last active February 18, 2020 18:59
Show Gist options
  • Save julp/5a66b79281ea6a0788c0ae524be42790 to your computer and use it in GitHub Desktop.
Save julp/5a66b79281ea6a0788c0ae524be42790 to your computer and use it in GitHub Desktop.
Dynamic SQL queries
<?php
// ev = escape value
function ev(object $dbh, $value) {
if (is_null($value)) {
return 'NULL';
} else if (is_int($value)) {
return $value;
} else if ($value instanceof \DateTimeImmutable) {
$value = $value->format('Y-m-d');
# /!\ no return here /!\
}
if ($dbh instanceof \PDO) {
return $dbh->quote($value);
} else if ($dbh instanceof \mysqli) {
return "'" . $dbh->real_escape_string($value) . "'";
} else {
throw new \Exception("I don't know how to handle an objet of class '" . get_class($dbh) . "'");
}
}
// ei = escape identifier
function ei(string $identifier): string {
return '`' . str_replace('`', '``', $identifier) . '`';
}
function update(object $dbh, string $table, array $columns, array $conditions = []): string {
// SET part
$set = [];
foreach ($colonnes as $column => $value) {
$set[] = ei($column) . ' = ' . ev($dbh, $value);
}
// WHERE part
if ($conditions) {
$where = [];
foreach ($conditions as $column => $value) {
$where[] = ei($column) . (is_null($value) ? ' IS ' : ' = ') . ev($dbh, $value);
}
} else {
$where = ['1=1'];
}
return 'UPDATE ' . ei($table) . ' SET ' . implode(', ', $set) . ' WHERE ' . implode(' AND ', $where);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment