Tuesday, 27 August 2013

mysql_insert_id(); keeps returning '0'

mysql_insert_id(); keeps returning '0'

I'm trying to grab the id after a query using mysql_insert_id();, but I'm
still getting 0 despite the fact that
I've placed it after the query itself and
I've made sure that the id (called P_Id) has AUTO_INCREMENT.
Code below:
$con=mysqli_connect(-connectiondetails-);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO clients (Name, Email, Address, Phone, Date, Service,
ExtraOne, ExtraTwo, ExtraThree, ExtraFour, ExtraFive) VALUES
('$_POST[name]','$_POST[email]','$_POST[address]','$_POST[phone]','$_POST[date]','$_POST[service]','$_POST[extra1]','$_POST[extra2]','$_POST[extra3]','$_POST[extra4]','$_POST[extra5]')";
$idit = mysql_insert_id();
echo $idit;
if (mysqli_query($con,$sql))
{
}
else
{
echo "Error message goes here: " . mysqli_error($con);
}
Thinking "Oh okay maybe I have to actually query it first", I did the
following but came up with the same result:
$con=mysqli_connect(-connectiondetails-);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO clients (Name, Email, Address, Phone, Date, Service,
ExtraOne, ExtraTwo, ExtraThree, ExtraFour, ExtraFive) VALUES
('$_POST[name]','$_POST[email]','$_POST[address]','$_POST[phone]','$_POST[date]','$_POST[service]','$_POST[extra1]','$_POST[extra2]','$_POST[extra3]','$_POST[extra4]','$_POST[extra5]')";
if (mysqli_query($con,$sql))
{
$idit = mysql_insert_id();
echo $idit;
}
else
{
echo "Error message goes here: " . mysqli_error($con);
}
Any idea where I went wrong? I've gone through other threads but nothing
seems to be working for me. Thanks in advanced.
EDIT: I have changed mysql_insert_id(); to mysqli_insert_id(); and this
time it didn't even return a 0, just blank.
EDIT 2: Thank you mbouzahir - your solution worked :)

No comments:

Post a Comment