Skip to content

Instantly share code, notes, and snippets.

@jehoshua02
Created December 19, 2011 11:24
Show Gist options
  • Save jehoshua02/1496745 to your computer and use it in GitHub Desktop.
Save jehoshua02/1496745 to your computer and use it in GitHub Desktop.
I know PHP. I know SQL. But I'd rather write a function in PHP to write SQL and put it in my Database class.
public function build_insert($fields_count, $values_count)
{
$indent = str_repeat(' ', 2);
$ph = '?';
$ph_tick = "`{$ph}`";
$ph_table = $ph_tick;
$ph_field = $ph_tick;
$ph_fields = implode(",\n{$indent}", array_fill(0, $fields_count, $ph_field));
$ph_value = sprintf('(%s)', implode(', ', array_fill(0, $fields_count, $ph)));
$ph_values = implode(",\n{$indent}", array_fill(0, $values_count, $ph_value));
$format_insert = "INSERT INTO %s (\n{$indent}%s\n)\nVALUES\n{$indent}%s;";
$sql = sprintf($format_insert, $ph_table, $ph_fields, $ph_values);
return $sql;
}

Example

$sql = $db->build_insert(5, 2);

Result

INSERT INTO `?` (
  `?`,
  `?`,
  `?`,
  `?`,
  `?`
)
VALUES
  (?, ?, ?, ?, ?),
  (?, ?, ?, ?, ?);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment