Function mysql_insert_id () returns only zero

1

Personally I'm having problems with the mysql_insert_id () function, when I use the form below the value returned is always "0" (zero). Can you help me?

The "add" function calls the "save" function.

OPEN_DATABASE FUNCTION

// ABRE A BASE DE DADOS
function open_database()
{
    try
        {
            $conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
            return $conn;
        }
    catch (Exception $e)
        {
            echo $e->getMessage();
            return null;
        }
}

ADD FUNCTION

// INSERE NOVO ORÇAMENTO
function add()
{
    if (!empty($_POST['budget']))
        {
            $budget = $_POST['budget'];
            save('budgets', $budget);
            //print_r($budget);
            //header('location: view.php?id='.$id);
        }
}

SAVE FUNCTION

// INSERE UM NOVO REGISTRO NO BANCO DE DADOS
function save($table = null, $data = null)
{
    $database = open_database();
    $columns = null;
    $values = null;
    foreach ($data as $key => $value)
        {
            $columns .= trim($key, "'") . ", ";
            $values .= "'$value', ";
        }
    // remover a ultima vÍrgula
    $columns = rtrim($columns, ', ');
    $values = rtrim($values, ', ');
    $sql = "INSERT INTO " . $table . " ($columns) " . "VALUES " . "($values);";
    //echo $sql;
    try
        {
            $database -> query($sql);
            $id = mysql_insert_id();
            header('location: view.php?id='.$id);
            $_SESSION['message'] = 'Registro cadastrado com sucesso!';
            $_SESSION['type'] = 'success';
        }
    catch (Exception $e)
        {
            $_SESSION['message'] = 'Nao foi possivel realizar a operacao!';
            $_SESSION['type'] = 'danger';
        }
    close_database($database);
}
    
asked by anonymous 28.06.2017 / 15:50

1 answer

2

You are using mysqli and in the line $id = mysql_insert_id(); you used mysql

You also have to pass the $database connection to the $id = mysqli_insert_id($database);

    ..........
    ..........
    try
    {
        $database -> query($sql);
        $id = mysqli_insert_id($database);
        header('location: view.php?id='.$id);
        $_SESSION['message'] = 'Registro cadastrado com sucesso!';
        $_SESSION['type'] = 'success';

    ..........
    ..........
    
28.06.2017 / 16:35