Alex Nicol
Alex Nicol

Reputation: 13

php if AND mysql empty

Database: Links

Table: Company (id INT, name VARCHAR)
Table: Employee (id INT, name VARCHAR, company_id INT)
Table: Links (id INT, name VARCHAR, employee_id)

The above eventually displays a list of links that a certain person from a certain company can click on.

I am trying to develop an update user page.

So far I have got drop downs for company and employee and tickboxes to highlight what the user can see.

I can parse these through a form quite happily. My question is:

How do I convert the following into a single line that I can replicate for the other 11 checkboxes?

if ($_POST[Protection]=1 AND *SEE BELOW*=0)
{
$sql="INSERT INTO links (ID, name, employee_id) VALUES ('', 'Protection', '$_POST[emp_id]')";
}

if ($_POST[Protection]=0 AND *SEE BELOW*=1)
{
//DROP From links
}


*FROM ABOVE*
$query= 'SELECT * FROM links'." WHERE id=$POST[id] AND name=Protection"; 
$result = mysql_query($query) or die ("Error in query: $query " . mysql_error()); 
$row = mysql_fetch_array($result); 
$num_results = mysql_num_rows($result);

Upvotes: 1

Views: 254

Answers (1)

Eric
Eric

Reputation: 123

You could create an array of the available checkboxes and iterate over them in a loop:

$checkboxes = array('Protection', 'AnotherOption', 'YetAnotherOption');

foreach ($checkboxes AS $key => $value)
{
    if (!isset($_POST[$value]) continue;

    if ($_POST[$value] == 1)
        mysql_query("INSERT INTO links (ID, name, employee_id) VALUES ('', '$value', '{$_POST['emp_id']}')");

    elseif ($_POST[$value] == 0)
        mysql_query("DELETE FROM links WHERE employee_id='{$_POST['emp_id']}' AND name='$value'");
}

OR

foreach ($_POST AS $key => $value)
{
    if (in_array($key, $checkboxes))
    {
        if ($value == 1)
            mysql_query("INSERT INTO links (ID, name, employee_id) VALUES ('', '$key', '{$_POST['emp_id']}')");

        elseif ($value == 0)
            mysql_query("DELETE FROM links WHERE employee_id='{$_POST['emp_id']}' AND name='$key'");
    }
}

Upvotes: 1

Related Questions