I need my form to post either INSERT or UPDATE data, depending on whether the column already exists. The INSERT query works fine, but the UPDATE doesn't. I guess this would be because the initial sql query ($query) is failing, more than likely because it is not finding the $Unique\_Ref POST data. If this is the case, how do I extract this single value from the $invoice\_data array?

This is the form page code:

```
if (isset($_GET['success']) && empty($_GET['success'])) {echo 'Record saved'; } else {if (empty($_POST) === false && empty($errors) === true) {$invoice_data = array(
    'Unique_Ref'            => mysqli_real_escape_string($conn, $_POST['Unique_Ref']),
    'Supplier_Name'         => mysqli_real_escape_string($conn, $_POST['Supplier_Name']),
    'Supplier_Invoice_Ref'  => mysqli_real_escape_string($conn, $_POST['Supplier_Invoice_Ref']),
    'Office'                => mysqli_real_escape_string($conn, $_POST['Office']),
    'Loss_Surplus_Amount'   => mysqli_real_escape_string($conn, $_POST['Loss_Surplus_Amount']),
    'Loss_Surplus_Currency' => mysqli_real_escape_string($conn, $_POST['Loss_Surplus_Currency']),
    'Outcome'               => mysqli_real_escape_string($conn, $_POST['Outcome']));

    save_invoice($invoice_data);header('Location: invoices.php?success'); exit();
    } else if (empty($errors) === false) {echo output_errors($errors);} ?> *html form....*

```

This is the save\_invoice() function:

```
function save_invoice($invoice_data) {
global $conn;
array_walk($invoice_data, 'array_sanitize');
$fields = '`' . implode('`, `', array_keys($invoice_data)) . '`';
$data   = '\'' . implode('\', \'', $invoice_data) . '\'';

$query  = mysqli_query($conn, "SELECT * FROM `invoicelog` WHERE `Unique_Ref` = '$Unique_Ref'");
$result = mysqli_num_rows($query);

if($result > 0) {
    mysqli_query($conn, "UPDATE `invoicelog` SET $fields = $data WHERE `Unique_Ref` = '$Unique_Ref'");
} else {
    mysqli_query($conn, "INSERT INTO `invoicelog` ($fields) VALUES ($data)");
}

```

Any suggestions would be very welcome. As I mentioned, the final INSERT query works fine, it's the UPDATE query which isn't functioning.