1
I am having problems with the function mysql_insert_id(), when I use the form below the value returned is always "0" (zero). Can 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);
}
						
Question: The record is saved correctly in the database?
– Woss
The old functions
mysql_do not launch Exception, thetry-catchis just for show.– rray
You’re probably using another driver to connect to the bank, which is good, since
mysql_is obsolete and has been discontinued. The answer depends on how your function isopen_database, include its content in the question.– bfavaretto
@bfavaretto is up to date...
– Flávio Kowalske
@Andersoncarloswoss yes, is saved normally...
– Flávio Kowalske
Lacked a
iin the call and pass the connection to function.– rray
That is to say,
mysqli_insert_id($database).– Woss