Skip to content

Instantly share code, notes, and snippets.

@fastslack
Created November 27, 2012 19:58
Show Gist options
  • Save fastslack/4156626 to your computer and use it in GitHub Desktop.
Save fastslack/4156626 to your computer and use it in GitHub Desktop.
insertRows example
/**
* Inserts a row into a table based on an associative array.
*
* @param string $table The name of the database table to insert into.
* @param array &$values A reference to an object whose public properties match the table fields.
* @param array $columns The name of the primary key. If provided the object property is updated.
*
* @return boolean True on success.
*
* @since 12.1
* @throws RuntimeException
*/
public function insertRows($table, $values, $columns = null)
{
$fields = array();
$newvalues = array();
// Iterate over the object variables to build the query fields and values.
foreach ($values as $k => $v)
{
// Only process non-null scalars.
if (is_array($v) or is_object($v) or $v === null)
{
continue;
}
// Ignore any internal fields.
if ($k[0] == '_')
{
continue;
}
// Ensure that only valid data parameters are set if they exist.
if ($columns !== null && in_array($k, $columns)) {
// Prepare and sanitize the fields and values for the database query.
$fields[] = $this->quoteName($k);
$newvalues[] = $this->quote($v);
}else if ($columns === null){
$fields[] = $this->quoteName($k);
$newvalues[] = $this->quote($v);
}
}
// Create the base insert statement.
$query = $this->getQuery(true);
$query->insert($this->quoteName($table))
->columns($fields)
->values(implode(',', $newvalues));
// Set the query and execute the insert.
$this->setQuery($query);
if (!$this->execute())
{
return false;
}
return true;
}
@eddieajau
Copy link

Close, but I still want it to quote the inner array or object.

@fastslack
Copy link
Author

Fixed line 38. Can you give me an example of values and ignore columns?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment