-1

我无法在 show_form() 函数中访问 $connection 变量。我收到未声明的变量错误。我需要做什么才能在函数中访问这个变量?

<html>
<body>
<?php
include('db.php');
$connection = mysqli_connect($db_host, $db_username, $db_password, $db_database);

    if (isset($_POST['submit-button'])){
        require_once 'process1.php';
        if($form_errors = validate_form())
        {
            show_form($form_errors);
        }
        else
        {
            process_1();
        }
    }
    else{
        show_form();
    }
?>
function show_form($errors = ''){
<form id='myForm'>

<?php

    echo "<SELECT id='test' >\n";
    echo "<option value=''></option>\n";

    if ($result = $connection->query("SELECT col1, col2 FROM table1 order by col1"))
    {
        while($row = $result->fetch_assoc()) 
        {
            echo "<option value='{$row['col1']}'>{$row['col2']}</option>\n"; 
        }
    }
    echo "</select>\n";
?>
</form>
<?php
}
?>
</body>
</html>
4

1 回答 1

0

每当您调用此函数时,将 $connection 变量作为参数传递

<?php function show_form($errors = '',$connection){?>
    <form id='myForm'>

    <?php

                echo "<SELECT id='test' >\n";
                echo "<option value=''></option>\n";

                if ($result = $connection->query("SELECT col1, col2 FROM table1 order by col1"))
                {
                    while($row = $result->fetch_assoc()) 
                    {
                        echo "<option value='{$row['col1']}'>{$row['col2']}</option>\n"; 
                    }
                }
                echo "</select>\n";
            ?>
    </form>
    <?php
    }
于 2013-05-24T15:52:03.560 回答