Version: v2.4.0
insert
Insert one or more records into a table.
insert($table, $values)
table [string]
The name of the table.
values [array]
The data to be inserted.
Return Value
[PDOStatement] The PDOStatement instance for the executed query.
$database->insert("account", [
"user_name" => "foo",
"email" => "foo@bar.com",
"age" => 25
]);
Last Insert ID
To get the inserted row ID, call
id() after insert().$database->insert("account", [
"user_name" => "foo",
"email" => "foo@bar.com",
"age" => 25
]);
$account_id = $database->id();
For Oracle, provide the primary key as the third parameter of
insert().$database->insert("ACCOUNT", [
"NAME" => "foo"
], "ID");
$account_id = $database->id();
Array Serialization
By default, array values are serialized with
serialize() before insertion. You can use [JSON] to store them with json_encode() instead.$database->insert("account", [
"user_name" => "foo",
"email" => "foo@bar.com",
"age" => 25,
"lang" => ["en", "fr", "jp", "cn"] // => \'a:4:{i:0;s:2:"en";i:1;s:2:"fr";i:2;s:2:"jp";i:3;s:2:"cn";}\'
]);
$database->insert("account", [
"user_name" => "foo",
"email" => "foo@bar.com",
"age" => 25,
"lang [JSON]" => ["en", "fr", "jp", "cn"] // => \'["en","fr","jp","cn"]\'
]);
Type Auto-Detection
Medoo automatically detects and binds data types before insertion for safer and more efficient writes.
class Foo {
var $bar = "cat";
public function __wakeup()
{
$this->bar = "dog";
}
}
$object_data = new Foo();
$fp = fopen($_FILES[ "file" ][ "tmp_name" ], "rb");
$database->insert("account", [
// String value.
"user_name" => "foo",
// Integer value.
"age" => 25,
// Boolean value.
"is_locked" => true,
// Array value.
"lang" => ["en", "fr", "jp", "cn"],
// Array value encoded as JSON.
"lang [JSON]" => ["en", "fr", "jp", "cn"],
// Object value.
"object_data" => $object_data,
// Large Objects (LOBs).
"image" => $fp
]);
Multi-Insertion
You can also insert multiple rows in a single call.
$database->insert("account", [
[
"user_name" => "foo",
"email" => "foo@bar.com",
"age" => 25,
"city" => "New York",
"lang [JSON]" => ["en", "fr", "jp", "cn"]
],
[
"user_name" => "bar",
"email" => "bar@foo.com",
"age" => 14,
"city" => "Hong Kong",
"lang [JSON]" => ["en", "jp", "cn"]
]
]);
PDOStatement
insert() returns a PDOStatement object, so you can call PDOStatement methods for additional details.$data = $database->insert("account", [
"user_name" => "foo",
"email" => "foo@bar.com",
"age" => 25
]);
// Returns the number of rows affected by the last SQL statement
echo $data->rowCount();
// Reference: https://php.net/manual/en/class.pdostatement.php
Using SQL Functions
You can use SQL functions through the raw object for advanced use cases. Read more at https://medoo.in/api/raw.
$database->insert("account", [
"user_name" => "bar",
"uid" => Medoo::raw("UUID()")
]);