Get Started

Upgrade

Where Syntax

Query

Aggregation

Fetch

Transaction

Management

Advanced

Raw object

PDO object

Debug

Information

version: 2.1.12

insert

Insert one or more records into the table.

insert($table, $values)
Return: [PDOStatement] The PDOStatement object.
$database->insert("account", [
	"user_name" => "foo",
	"email" => "foo@bar.com",
	"age" => 25
]);

Last insert ID

If you want the row ID after the insertion, you need to call the lastInsertId() alone and get it.

$database->insert("account", [
	"user_name" => "foo",
	"email" => "foo@bar.com",
	"age" => 25
]);

$account_id = $database->id();

For Oracle, you need to provide the primary key as the last parameter for insertation.

$database->insert("ACCOUNT", [
	"NAME" => "foo"
], "ID");

$account_id = $database->id();

Array serialization

By default, the array data will be serialized by serialize() before insertion, but you can assign it as JSON to be serialized by json_encode().

$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 will automatically detect the data type before insertion and optimize it to store it into the database.

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 data multiply.

$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

The returned object of insert() is PDOStatement, so you can use its methods to get more information.

$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();

// Read more: http://php.net/manual/en/class.pdostatement.php

Using SQL functions

You can now use SQL functions with the raw object for complex usage. Read more from https://medoo.in/api/raw.

$database->insert("account", [
	"user_name" => "bar",
	"uid" => Medoo::raw("UUID()")
]);