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);
}