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.
I have an insert operation taking place and I want to get the id of the inserted row.
Here's my code:
$qry="INSERT INTO tablename(content) VALUES('".$content."')";
setData($qry);
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;
        }
    }
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() 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().
Try : $con->insert_id;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With