空或不空允许使用php插入

时间:2018-04-28 03:00:16

标签: php jquery html mysqli

If($_POST){
    $validator = array ('success' => false,  'message' => array());
    $a = $_POST['name'];
    $b = $_POST['sex'];
    $c = isset ($_POST['national'])?$_POST['national']:0;

    $sql="INSERT INTO tblstudent VALUES('$a','$b','$c')";
    $query=$connect->query($sql);

    if($query ===true){
        $validator['success'] = true;
        $validator['message '] = "added";
    }else{
        $validator['success'] = false;
        $validator['message '] = "error";

        //close connection 
        $connect->close ();

        Echo json_encode($validator);
    }

变量$c可以输入也可以不输入。如果$c为空,我想设置它=0。上面的代码不起作用。问题是变量$c

2 个答案:

答案 0 :(得分:0)

您在"语句中遗漏了sql,我也用if if迭代替换了$c值分配三元运算符,以便您可以轻松地细分代码,并使用以下代码转换代码准备好防止sql注入攻击的语句

If($_POST)
{
$validator = array ('success' => false,  'message' => array());
$a = $_POST['name'];
$b = $_POST['sex'];

if(isset($_POST['national']))
{
c=$_POST['national'];
}
else
{
c=0;
}

$sql=$connect->prepare("INSERT INTO tblstudent VALUES(?,?,?)";
$sql->bind_param("sss",$a,$b,$c);

if($sql->execute())
{
    $validator['success'] = true;
    $validator['message '] = "added";
}else{
    $validator['success'] = false;
    $validator['message '] = "error";

    //close connection 
    $connect->close ();

    Echo json_encode($validator);
}

答案 1 :(得分:0)

当您使用"时,未添加$connect->query来结束您的sql查询,并且未在查询中传递列名。尝试以下,

<?php
if(isset($_POST) && array_filter($_POST)){
    $validator = array ('success' => false,  'message' => array());
    if(!empty($_POST['name']) && !empty($_POST['sex'])){
        $name = $connect->real_escape_string($_POST['name']);
        $sex = $connect->real_escape_string($_POST['sex']);
        $national = ($_POST['national']) ? $connect->real_escape_string($_POST['national']) : 0;        
        $sql = "INSERT INTO `tblstudent` (`name`,`sex`,`national`) VALUES('{$name}','{$sex}','{$national}')";       
        $validator = ($connect->query($sql)) ? array('success' => true, 'message' => 'added') : array('success' => false, 'message' => 'error');        
    }else{
        $validator = array ('success' => false,  'message' => 'error');
    }    
    $connect->close();
    echo json_encode($validator);
    exit();
}
?>