mysql 插入怎么知道id_如何知道刚刚插入数据库那条数据的id
如何知道剛剛插入數據庫那條數據的id
一、總結
一句話總結:這些常見功能各個框架里面都有,可以查看手冊,thinkphp里面是$userId = Db::name('user')->getLastInsID();
1、在mysql和mysqli中如何選擇?
用mysqli,php官方推薦
2、mysqli中如何查找到剛剛出入數據庫的那條數據的id?
mysqli對象的indert_id屬性
$mysqli->insert_id
二、PHP如何找到剛剛插入數據庫的一條數據的ID?
$_title=$_POST['input_title'];
$_described=$_POST['described'];
mysql_query("insert into questionnaire (quesTitle,quesDescribe,createTime) values('$_title','$_described',now())");
header(index.php?quesid=剛剛插入的那個編號)
如上所述,我剛剛插入的一條數據,現在要立刻跳到該數據自動生成的id的頁面去,怎么獲取呢??
你看看 mysql_insert_id 這個函數. 獲取上一步insert 插入成功的id, 不成功的時候是沒有值的
mysql_insert_id() 函數返回上一步 INSERT 操作產生的 ID。 沒事多自己百度一下,多看手冊,別一有問題就到處發帖,這種只要一分鐘就能知道的答案 ,你卻要花十幾分鐘,甚至幾個小時,甚至沒人回答,我只能說一句,哥們 你這是何苦呢?
mysql_insert_id()將 MySQL 內部的 C API 函數 mysql_insert_id()的返回值轉換成 long(PHP 中命名為 int)。如果 AUTO_INCREMENT 的列的類型是 BIGINT,則 mysql_insert_id()返回的值將不正確??梢栽?SQL 查詢中用 MySQL 內部的 SQL 函數 LAST_INSERT_ID()來替代。
例子一:]mysql_insert_id()]例子b]b]
function mysql_insert_id ($link_identifier = null) {}/**
* @deprecated 5.5
* Get result data
* @link http://php.net/manual/en/function.mysql-result.php
* @param resource $result
* @param int $row
* The row number from the result that's being retrieved. Row numbers
* start at 0.
*
* @param mixed $field [optional]
* The name or offset of the field being retrieved.
*
*
* It can be the field's offset, the field's name, or the field's table
* dot field name (tablename.fieldname). If the column name has been
* aliased ('select foo as bar from...'), use the alias instead of the
* column name. If undefined, the first field is retrieved.
*
* @return string The contents of one cell from a MySQL result set on success, or
* false on failure.
* @since 4.0
* @since 5.0*/
$mysqli->insert_id
1 Example #1 $mysqli->insert_id example
2
3 面向對象風格4
5 <?php6 $mysqli = new mysqli("localhost", "my_user", "my_password", "world");7
8 /*check connection*/
9 if (mysqli_connect_errno()) {10 printf("Connect failed: %s\n", mysqli_connect_error());11 exit();12 }13
14 $mysqli->query("CREATE TABLE myCity LIKE City");15
16 $query = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";17 $mysqli->query($query);18
19 printf ("New Record has id %d.\n", $mysqli->insert_id);20
21 /*drop table*/
22 $mysqli->query("DROP TABLE myCity");23
24 /*close connection*/
25 $mysqli->close();26 ?>
thinkphp 5.0
多去查看參考手冊,里面肯定有
insert 方法添加數據成功返回添加成功的條數,insert 正常情況返回 1
添加數據后如果需要返回新增數據的自增主鍵,可以使用getLastInsID方法:
Db::name('user')->insert($data);
$userId = Db::name('user')->getLastInsID();
或者直接使用insertGetId方法新增數據并返回主鍵值:
Db::name('user')->insertGetId($data);
insertGetId 方法添加數據成功返回添加數據的自增主鍵
總結
以上是生活随笔為你收集整理的mysql 插入怎么知道id_如何知道刚刚插入数据库那条数据的id的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: zephir mysql_用Zephir
- 下一篇: db2 mysql sql server