问题描述
我知道这个问题已经回答了很多次.我从这里尝试了一些解决方案,但没有任何效果.我没有使用任何PHP框架.
I know this question has been answered many times. I tried a few of the solutions from here but nothing worked. I'm not using any PHP framework.
我正在执行插入操作,我想获取插入行的ID.
I have an insert operation taking place and I want to get the id of the inserted row.
这是我的代码:
$qry="INSERT INTO tablename(content) VALUES('".$content."')";
setData($qry);
setData()是一个用户定义的函数,它会执行插入操作.
setData() is a user defined function which does insert operation.
//for data submit
function setData($qry)
{
$obj=new DBCon();
$res=$obj->submitQuery($qry);
return $res;
}
//fetches result
function getData($qry)
{
$obj=new DBCon();
$res=$obj->selectQuery($qry);
return $res;
}
这是我为建立数据库连接而制作的类:
This is the class I made for establishing database connectivity:
class DBCon
{
private function getConnection()
{
// hostname, username, password, database
$con=mysqli_connect("localhost","root","","dbname")OR die('Could not Connect the Database');
return $con;
}
public function closeCon()
{
mysqli_close($con);
}
public function submitQuery($qry)
{
$result=0;
$con=$this->getConnection();
$result=mysqli_query($con,$qry);
return $result;
}
public function selectQuery($qry)
{
$con=$this->getConnection();
$res=mysqli_query($con,$qry);
return $res;
}
}
要获取最后插入的ID,我编写了以下查询,但未产生任何结果:
To obtain the last inserted id, I wrote the following query but it did not yield any result:
SELECT LAST_INSERT_ID() FROM tablename
还有其他方法可以得到这个吗?
Is there any other method to get this?
推荐答案
LAST_INSERT_ID()
仅返回MySQL服务器为AUTO_INCREMENT
列自动生成的值;当您插入特定值时,不会自动生成,LAST_INSERT_ID().
LAST_INSERT_ID()
only returns values that have been auto-generated by the MySQL server for an AUTO_INCREMENT
column; when you insert a specific value, no auto-generation takes place and no value will be returned by LAST_INSERT_ID().
尝试:$con->insert_id;
这篇关于PHP的-获取最后一个插入ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!