Last active
February 27, 2018 15:26
-
-
Save chapeupreto/cd42b6dff88b7e230c3bcf13fb355fe1 to your computer and use it in GitHub Desktop.
obtem SQL crua
This file contains hidden or 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 | |
function getRawSql(string $sql, array $inputs) | |
{ | |
foreach ($inputs as $input) { | |
$index = strpos($sql, '?'); | |
$f = substr($sql, 0, $index); | |
$f .= is_string($input) ? "'" . $input . "'" : $input; | |
$t = substr($sql, $index + 1); | |
$sql = $f . $t; | |
} | |
return $sql; | |
} | |
// Exemplo de uso: | |
$sql = "select * from usuarios where id = ? and login = ? and senha = ? and data >= ?"; | |
$inputs = [22, 'superman', 'superpowerful', '2017-02-10']; | |
echo getRawSql($sql, $inputs); | |
// Saida: select * from usuarios where id = 22 and login = 'superman' and senha = 'superpowerful' and data >= '2017-02-10' |
Author
chapeupreto
commented
Jun 26, 2017
/**
* gera SQL crua de insert
*
* @param string $tabela nome da tabela
* @param string $keys nomes das colunas separadas por vírgula
* @param array $dados array contendo os dados a serem resolvidos
* @return string
*/
function rawInsert($tabela, $keys, array $dados)
{
$sql = "INSERT INTO ${tabela} (";
$sql .= $keys . ')';
$sql .= 'VALUES (';
$s = '';
foreach ($dados as $dado) {
$s .= is_string($dado) ? "'${dado}'" : $dado;
$s .= ', ';
}
$s = rtrim($s, ', ');
return $sql . $s . ')';
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment