输入发送空值的无线电项目

时间:2013-05-11 05:45:19

标签: php sql null

你好我创建和无限子类别系统,一切都很好,除了代码创建新类别...

Root是“NULL”,所以我无法创建<input type="radio" name="parent_id" value="">在数据库中“写”空值。

如果我没有设置值,我会得到一个未定义的索引错误..我已尝试过isset,为空,is_null 但他们似乎都有问题,

isset($var) is FALSE 
empty($var) is TRUE 
is_null($var) is TRUE 

isset($novar) is FALSE 
empty($novar) is TRUE 
is_null($novar) gives an Undefined variable error 

这是我的代码,所以你可以看到我想要做什么。

//Check to see if the form has been submitted
if(isset($_POST['submit'])){

    //protect and then add the posted data to variables
    $name = protect($_POST['name']);
    $parent_id = $_POST['parent_id'];

    //check to see if a name was set
    if(!$name){
        //if any weren't display the error message
        echo "<center>Necesitas llenar todos los campos</center>";
    }else{
        //Check if the wanted name is more than 99 or less than 2 charcters long
        if(strlen($name) > 99 || strlen($name) < 2){
            //if it is display error message
            echo "<center>La categoría no puede rebasar los 100 caracteres!</center>";
        }else{


            if(is_null($parent_id)){

            $res = mysql_query("INSERT INTO `category` ( `name`) VALUES('".$name."')");

            echo "<center>Creaste la categoría correctamente!</center>";

            }
            else {

                $res = mysql_query("INSERT INTO `category` (`parent_id`, `name`) VALUES('".$parent_id."','".$name."')");

            echo "<center>Creaste la categoría correctamente!</center>";



                            }
                        }
                    }
}

代码实际上是有效的&amp;创建类别!

但是如果我创建一个根类别,即使成功创建类别,它也会在“parent_id”上显示未定义索引的错误,

¿我怎么摆脱那个错误?

1 个答案:

答案 0 :(得分:1)

如果我理解正确,请尝试更改

if(is_null($parent_id)){
$res = mysql_query("INSERT INTO `category` ( `name`) VALUES('".$name."')");
echo "<center>Creaste la categoría correctamente!</center>";
}
else {
    $res = mysql_query("INSERT INTO `category` (`parent_id`, `name`) VALUES('".$parent_id."','".$name."')");
echo "<center>Creaste la categoría correctamente!</center>";

if(isset($_POST['parent_id']) && $_POST['parent_id']){
    $parent_id = $_POST['parent_id'];
    $res = mysql_query("INSERT INTO `category` (`parent_id`, `name`) VALUES('$parent_id','$name')");
} else {
    $res = mysql_query("INSERT INTO `category` (`name`) VALUES('$name')");
}

if ($res) {
    echo "<center>Creaste la categoría correctamente!</center>";
} else {
    echo "<center>Error creating a category!</center>";
}

并在脚本开头删除或评论$parent_id = $_POST['parent_id'];

$name = protect($_POST['name']);
//$parent_id = $_POST['parent_id'];