Mihai.N
Mihai.N

Reputation: 49

If in array and database

I have some issues with the following code. In my form col6 and col7 are not defined in every case.

 $data = Array (
    'col1' => time(),
    'col2' => $_SESSION['user'],
    'col3' => $_POST['incr'],
    'col4' => 0,
    'col6'=>$_POST['incit'],
    'col7'=>$_POST['incex']
    );


$db->where ('id', $_POST['incag']);
$id = $db->update ('table', $data);

How can I make my $datavariable if $_POST['incit'] is not set, to delete col6 from array.

If column remains, the value in database is set to 0 or null. The value must be like POST in order not to be changed.

Upvotes: 0

Views: 50

Answers (2)

Pathik Vejani
Pathik Vejani

Reputation: 4491

You need to use isset():

<?php 
$data = Array (
'col1' => time(),
'col2' => $_SESSION['user'],
'col3' => $_POST['incr'],
'col4' => 0,
'col7'=>$_POST['incex']
); 
if(isset($_POST['incit']) && !empty($_POST['incit'])) {
   $data['col6'] = $_POST['incit'];
}
?>

See more info about isset() here.

Upvotes: 0

Endijs
Endijs

Reputation: 550

 $data = [
    'col1' => time(),
    'col2' => $_SESSION['user'],
    'col3' => $_POST['incr'],
    'col4' => 0,
    'col7' => $_POST['incex'],
];
if (isset($_POST['incit'])) {
    $data['col6'] = $_POST['incit'];
}

One more thing - I hope that your $db layer is handling all SQL injection related things. As you are not doing any filtering, it can turn ugly very fast.

Upvotes: 2

Related Questions