Last active
February 18, 2020 18:59
-
-
Save julp/5a66b79281ea6a0788c0ae524be42790 to your computer and use it in GitHub Desktop.
Dynamic SQL queries
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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