public function processInsert(DatabaseLayer\Insert $thing) { // SELECTORS if (count($thing->getTables()) > 1) { throw new Exception("Active Record Cannot insert into more than one table at a time!"); } $tables = $thing->getTables(); $table = end($tables); $updates = array(); foreach ($thing->getData() as $key => $value) { $key = trim($key, "\""); $key = trim($key, "`"); if (is_object($value) || is_array($value)) { $value = JsonPrettyPrinter::Json($value); } $value_slashed = addslashes($value); if ($value === null) { $updates['columns'][] = $key; $updates['values'][] = 'NULL'; } else { $updates['columns'][] = $key; $updates['values'][] = $value_slashed; } } $selector = "INSERT INTO {$table->getName()} "; $data = "(" . implode(", ", $updates['columns']) . ") VALUES ('" . implode("', '", $updates['values']) . "')"; $query = "{$selector}\n{$data}"; $this->query($query); $insertId = $this->lastInsertId(); return $insertId; }
/** * @expectedException \Thru\ActiveRecord\DatabaseLayer\Exception * @expectedExceptionMessage Active Record Cannot insert into more than one table at a time! */ public function testInsertIntoTwoTablesFails() { $insert = new DatabaseLayer\Insert("test_models"); $insert->setTables(array("tm" => new DatabaseLayer\Table("test_models"), "tmb" => new DatabaseLayer\Table("test_model_bad"))); $insert->execute(); }
public function processInsert(DatabaseLayer\Insert $thing) { // SELECTORS if (count($thing->getTables()) > 1) { throw new Exception("Active Record Cannot insert into more than one table at a time!"); } $tables = $thing->getTables(); $table = end($tables); $data = $thing->getData(); $keys = []; $values = []; foreach ($data as $key => $value) { $key = trim($key, "`"); if (is_object($value) || is_array($value)) { $value = JsonPrettyPrinter::Json($value); } $keys[] = $key; $value_slashed = str_replace("'", "''", $value); if ($value === null) { $value = "NULL"; } elseif (is_numeric($value)) { // Do nothing } else { $value = "'{$value_slashed}'"; } $values[] = $value; } $selector = "INSERT INTO {$table->getName()} "; $columns = "(`" . implode("`, `", $keys) . "`)"; $values = "(" . implode(", ", $values) . ")"; $query = "{$selector}\n{$columns} \nVALUES \n{$values}"; // echo "*** Just before query(): ".$thing->getModel() . "\n"; $this->query($query, $thing->getModel()); $insertId = $this->lastInsertId(); return $insertId; }