function running in foreach loop

2019-08-20 09:23发布

问题:

thank you for taking time to look at this. I have been dealing with this annoying foreach loop. Here is what I am trying to do.

I have the first page "form.php". On this page I have check boxes. Each check box is generated from a database table. Here is the code:

<?php
include("config.php");
$mysqli = new mysqli($host, $db_uname, $db_pass, $db);
$query = "SELECT * FROM `plugins` WHERE 1";

if ($result = $mysqli->query($query)) {

    echo '<form action="test.php" method="post">
            <input name="gname" placeholder="Group Name..."/>
                <table width="200">
                    ';

    while ($row = $result->fetch_assoc()) {

echo '<tr><td>
        <label>
            <input type="checkbox" value="'.$row["plugin"].'" name="checkbox[]">
            '.$row["plugin"].'
        </label>
        </td></tr>';

    }
    echo '
            </table>
            <select name="permplugin">
            <option>Select One...</option>';

$query2 = "SELECT * FROM `permission_types` WHERE 1";

if ($result2 = $mysqli->query($query2)) {
echo '<h3>Select Permission format below</h3><hr />';
while ($row2 = $result2->fetch_assoc()) {
echo '
<option value="'.$row2["plugin_name"].'">'.$row2["plugin_name"].'</option>';
}
echo '
</select>
<br />
<input name="" type="reset"><input name="" type="submit">
</form>';
}
}
?>

Now after that it sends the checked boxes to "test.php" here is the code for that:

<?php
if(!empty($_POST['checkbox']) || !empty($_POST['select']) || !empty($_POST['gname'])) {
    echo '<h1>'.$_POST['gname'].'</h1>';

    $check1 = $_POST['checkbox'];
    foreach($check1 as $check) {
        include "functions.php";
            checkboxes($check);

    }
    echo '<h3>Selected Permission format below</h3><hr />';
    echo $_POST['permplugin'];

} else {

    echo "please select atleast one plugin.";
}
?>

The functions page code looks like this:

<?php
//all functions are here.
function checkboxes($check){
$mysqli_perm = new mysqli("localhost", "uname", "pword", "tcordero_permnodes");
$query_perm = "SELECT * FROM permission_nodes WHERE plugin = `$check`";
if ($result_perm = $mysqli_perm->query($query_perm)) {
    echo $check;
    /* fetch associative array */
    while ($row_perm = $result_perm->fetch_assoc()) {
        echo $row_perm['node'].'<br />';

    }
    unset($check);
}
}

When I run the test.php I get this error: Fatal error: Cannot redeclare checkboxes() (previously declared in C:\xampp\htdocs\TPYC\functions.php:3) in C:\xampp\htdocs\TPYC\functions.php on line 15

What am I doing wrong?

回答1:

You need to take the include out of the foreach loop. Try this:

include "functions.php";
foreach($check1 as $check) {
    checkboxes($check);
}