Skip to content

Instantly share code, notes, and snippets.

@chapeupreto
Last active February 27, 2018 15:26
Show Gist options
  • Save chapeupreto/cd42b6dff88b7e230c3bcf13fb355fe1 to your computer and use it in GitHub Desktop.
Save chapeupreto/cd42b6dff88b7e230c3bcf13fb355fe1 to your computer and use it in GitHub Desktop.
obtem SQL crua
<?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'
@chapeupreto
Copy link
Author

chapeupreto commented Feb 27, 2018

/**
 * 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