Undefined variable notice in PHP code
Question
I'm getting
"Undefined variable: html in on line $html .= generateOption($optstyle.'option', $level, $data, $padding);
"
What's wrong with my function?
function generateOptions($parent, $level, $padding, $menu, $db)
{
$result=$db->query("SELECT id, name FROM menu WHERE parent='$parent' AND showinmenu='$menu'");
$spacer = ' ';
$padding = str_repeat($spacer, $level);
while($data=$result->fetch_row()){
$children_html = generateOptions($data[0], $level+1, $padding, $menu,$db);
$optstyle = empty($children_html) ? 'std' : 'bold';
$html .= generateOption($optstyle.'option', $level, $data, $padding); (this line)
$html .= $children_html;
}
return $html;
}
Solution
You didn't define $html before you tried to use it.
Try adding $html = "";
after $padding = str_repeat($spacer, $level);
OTHER TIPS
You'll have to initialise the $html
before you start appending to it. Think about $html .= something
like $html = $html . something
and you should see the issue.
Also, your query is insecure. Make sure you escape everything - just in case.
Just declare the variable first before appending to it. Using the dot operator just appends content. If you simply use $html = '';
before your loop the warning should be gone.
function generateOptions($parent, $level, $padding, $menu, $db)
{
$html = ''; # define `$html` first
$result = $db->query("SELECT id, name FROM menu WHERE parent='$parent' AND showinmenu='$menu'");
$spacer = ' ';
$padding = str_repeat($spacer, $level);
while($data = $result->fetch_row())
{
$children_html = generateOptions($data[0], $level+1, $padding, $menu,$db);
$optstyle = empty($children_html) ? 'std' : 'bold';
$html .= generateOption($optstyle.'option', $level, $data, $padding);
$html .= $children_html;
}
return $html;
}
As mentioned by others, you should escape your $parent
and $menu
variables to prevent SQL injection.
begin the code with this :
$html = "";
in begin line insert code
if (!isset($html)) {
$html = '';
};
$html .= generateOption($optstyle.'option', $level, $data, $padding); (this line)
$html .= $children_html;
Remove the dot in front of the first = in the first line.