-1

I would like to return the ID "setsId" after I insert values in the the Sets table.

This is the error I receive: Call to undefined function last_insert_id().

Here is my code:

if($_POST[reps]=="")
{
echo "Record can not be added. All fields are mandatory";
echo '<br>';
}
else
{
    $con = mysqli_connect(); //removed for privacy

    if (mysqli_connect_errno())
    {
       echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }

    $sql="INSERT INTO Sets (exerciseId, bandId, reps, notes) 
    VALUES ('$_POST[exerciseId]',
        '$_POST[bandId]',
        '$_POST[reps]',
        '$_POST[notes]')";

    $sId=last_insert_id();

    if (!mysqli_query($con,$sql))
    {
        die('Error: ' . mysqli_error($con));
    }


    echo '<div id ="error">';
    echo 'SUCCESS!';
    echo '<br>';
    echo "1 record added";
    echo '<br>';
    echo '</div>';
    mysqli_close($con);
}
include ('ptfooter.html');
?>

Could someone please let me know how I am using the function last_insert_id() incorrectly so that it would cause an error?

user2884789
  • 373
  • 1
  • 8
  • 21

1 Answers1

7

last_insert_id is the name of a MySQL function. The corresponding mysqli function is called mysqli_insert_id. Use that instead.

But you can't call that function if you haven't executed your insert query yet. Make sure that your insert is executed (and succeeded) before you call that function.

Mat
  • 202,337
  • 40
  • 393
  • 406