insert
插入数据到表中
insert($table, $data)
table [string]
表名.
data [array]
插入到表里的数据.
Return: [number] 返回插入的id
$last_user_id = $database->insert("account", [ "user_name" => "foo", "email" => "foo@bar.com", "age" => 25 ]);
插入ID
如果你想要获取最后插入行的ID,你需要单独调用 id()
方法
$database->insert("account", [ "user_name" => "foo", "email" => "foo@bar.com", "age" => 25 ]); $account_id = $database->id();
序列化数组
默认情况下,你要将数组插入会被序列化serialize()
, 也可以使用 JSON 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"]' ]);
类型自动检测
Medoo将在插入之前自动检测数据类型,并将其优化以存储到数据库中。
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 ]);
多条数据插入
可以同时插入多条数据.
$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()返回的是PDOStatement对象,你可以通过它获取更多信息
$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
使用 SQL 函数
在一些特殊的情况下,您可能需要使用SQL函数来处理数据。在字段前加入#号即可
$last_user_id = $database->insert("account", [ "user_name" => "bar", "#uid" => "UUID()" ]);