我无法在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>
答案 0 :(得分: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
}