PHP MySql - 注意:未定义的变量错误

时间:2014-05-01 10:24:29

标签: php mysql

我有这个Code For Show在Dropdonn菜单中选择了已批准的项目:

PHP:

  if (!isset($form['approved']) || $form['approved'] == '0')
     $approved0 = 'selected';
  elseif (isset($form['approved']) && $form['approved'] == '1')
     $approved1 = 'selected';
  else
     $approved2 = 'selected';

HTML:

<select class="form-control" name="approved" class="formEditSelect">
     <option value="1" ' . $approved1 . '>Active</option>
     <option value="0" ' . $approved0 . '>Inactive</option>
     <option value="2" ' . $approved2 . '>Expired</option>
</select>

现在我看到了这个错误:

Notice: Undefined variable: approved1 in C:\xampp\htdocs\test\edit.php on line 207

Notice: Undefined variable: approved2 in C:\xampp\htdocs\test\edit.php on line 207

我如何修复此错误?

3 个答案:

答案 0 :(得分:1)

首先使用空白或某些值初始化变量

$approved1 = '';

导致您的vars处于条件状态,因此默认将是未声明的,因此首先将其初始化

或使用isset()empty()进行检查 喜欢: -

$approved1 = (!empty($approved1) ? $approved1 : '');

所以你的代码将是

$approved0 ='';
$approved1 ='';
$approved2 ='';
if (!isset($form['approved']) || $form['approved'] == '0')
     $approved0 = 'selected';
  elseif (isset($form['approved']) && $form['approved'] == '1')
     $approved1 = 'selected';
  else
     $approved2 = 'selected';

答案 1 :(得分:1)

试试这个:

$approved0=null;
$approved1=null;
$approved2 = null;

if (!isset($form['approved']) || $form['approved'] == '0')
     $approved0 = 'selected';
elseif (isset($form['approved']) && $form['approved'] == '1')
     $approved1 = 'selected';
else
     $approved2 = 'selected';

答案 2 :(得分:0)

首先声明$approved1 = null;$approved2 = null;$approved1 = ''; 你应该首先初始化这些变量