PHP form işaretleyin ve tanımsız indeksi

3 Cevap php

Bir un-kontrol onay kutusu ile bir form göndererek zaman bir "Undefined index" hatası alıyorum. Her yayınlanmıştır değerine kontrol bir "isset" veya "boş" çalışan dışında başka bir yolu var mı?

Ben bu Question baktım ve sorun bu tek çözüm olduğuna inanan yaşıyorum.

Below is some example code: EDIT: please not that these are not the actual names of the tables columns; they are named uniquely (like "postAddress, displayPhone, student, etc.)

3 Cevap

Bir onay kutusu işaretli olup olmadığını kontrol eden bir fonksiyon yazabiliriz:

function checkbox_value($name) {
    return (isset($_POST[$name]) ? 1 : 0);
}

Şimdi bu gibi sorguda bu işlevi çağırır:

$sql =  'UPDATE table SET '.
        'checkbox1 = '. checkbox_value('checkbox1') .','.
        'checkbox2 = '. checkbox_value('checkbox2') .','.
        'checkbox3 = '. checkbox_value('checkbox3') .','.
        'checkbox4 = '. checkbox_value('checkbox4') .','.
        'checkbox5 = '. checkbox_value('checkbox5') .','. "LIMIT 1";

Eğer bir açık / kapalı onay kutusunu isterseniz onay kutusunu yazmadan önce gizli bir değer yazabilirsiniz.

<input type="hidden" name="checkbox1" value="no" />
<input type="checkbox" name="checkbox1" value="yes" />

Bu her zaman (onay kutusu varsayılan olarak işaretli sürece varsayılan) da yok, bir değer döndürür ya da evet olacaktır.

Sen FILTER_VALIDATE_BOOLEAN ile filter functions ile giriş doğrulamak.

Onun kolay Bunun için bir işlev yazarsanız, formCheckbox ($ isim) gibi değerler için seçenekleri ile ('on' değeri onay kutusu varsayılan olarak kontrol edilir anlamına gelir), nitelikleri, vb

aşağıdakileri deneyin

<?php
//first part of the query
$query = "UPDATE table SET ";

$howManyCheckboxes = 5;
//for every checkbox , see if it exist , if it is, add it to the query
for($i=1;$i<=$howManyCheckboxes;$i++)
{
   if(isset($_POST['checkbox'.$i]))
   {
      $query = $query . " checkbox".$i."='".escape($_POST['checkbox'.$i])."',";
   }
}
//lets remove the last coma
$query = substr($query,0,-1);
//add the rest of the query
$query = $query . " LIMIT 1";

$result = mysql_query( $query );
if( ! $result ) echo "um, not everything went as expected.";
?>