为什么我收到有关未定义索引的错误?

时间:2014-12-04 12:41:22

标签: php mysql ajax

由于我的选择表单,我收到错误。我如何将选择表单放入我的php文件中?

这是我的代码:

<select name='md' multiple="yes" size="10">
    <optgroup label="Оpel">
        <option value="Astra" name='Ast'>Astra</option>
    </optgroup>
    <optgroup label="Nissan">        
        <option value="Pulsar" name='Puls'>Pulsar</option>
        <option value="Almera" name='Alm'>Almera</option>
    </optgroup>
    <optgroup label="Honda">
        <option value="Civic" name='Civ'>Civic</option>
    </optgroup>     
    <optgroup label="Audi">
        <option value="Q7" name='Q'>Q7</option>                 
    </optgroup>

    <optgroup label="BMW">
        <option value="M3" name='M'>M3</option>
    </optgroup>
    <optgroup label="Renault">
        <option value="Megane" name='Meg'>Megane</option>
    </optgroup>
    <optgroup label="Mercedes">
        <option value="G-Class" name='G'>G-Class</option>
    </optgroup>
</select></br></br>

Цвят :
<select name='col' size='5'>
    <option value='white' name='wh'>Бял</option>
    <option value='black' name='bl'>Черен</option>
    <option value='yellow' name='ye'>Жълт</option>
    <option value='brown' name='br'>Кафяв</option>
    <option value='grey' name='gr'>Сив</option>
</select></br></br>

我的php代码:

 $md = $_POST['md'];
 $col = $_POST['col'];

某处我看到我应该使用ajax吗?有必要吗?

3 个答案:

答案 0 :(得分:0)

尝试

if(isset($_POST['md'])){
  $md = $_POST['md'];
}else{
  $md = '';
} 

if(isset($_POST['col'])){
 $col = $_POST['col'];
}else{
  $col = '';
}

$md = (isset($_POST['md'])) ? $_POST['md'] : ''; 
$col = (isset($_POST['col'])) ? $_POST['col'] : '';

答案 1 :(得分:0)

您的PHP代码显示“注意:未定义索引:...”,因为您最初打开文件时在选择框中没有选择任何内容。要防止它,请使用if (isset(...))

if (isset($_POST['md']) {
  $md = $_POST['md'];
} else {
  $md = '';
}
if (isset($_POST['col']) {
  $col = $_POST['col'];
} else {
  $col = '';
}

或者您可以使用三元运算符作为更短的解决方案:

$md = (isset($_POST['md'])) ? $_POST['md'] : '';
$col = (isset($_POST['col'])) ? $_POST['col'] : '';

答案 2 :(得分:0)

因为我认为您正在接收多个选择的数组变量。使用数组存储数据。像这样

    <label for="aoi">Area of Interest:</label>
      <select id="sel_aoi" name="aoi[]" multiple="multiple">
        <option value="hr-executive">HR Executives</option>
        <option value="sr-manager">Sr. Manager</option>
        <option value="service-advisor">Service Advisor</option>
        <option value="production">Production Engineer</option>
        <option value="mechanical">Mechanical Engineer</option>
      </select>


    $aoi = implode(',', $_POST['aoi']);