插入查询缺失列

时间:2017-01-25 21:14:50

标签: php mysql arrays

我有一个使用$ _post来访问insert.php页面的表单。当我执行print_r

时,$ _post信息看起来像这样
Array ( 
    [extension] => Array ( 
        [0] => 100 
        [1] => 101 
        [2] => 102 
        ) 
    [secret] => Array ( 
        [0] => a467ca4044f298eff15a26e59f39fe21 
        [1] => 0c4275de171ef363b77aa6aae27afff1 
        [2] => c1951bfb07ed6a833d6d785ff4e19123 
        ) 
    [phone] => Array ( 
        [0] => 80828703658A 
        [1] => 80828703D858 
        [2] => 80828703F866 
        ) 
    [template] => Array ( 
        [0] => Another 600 Template 
        [1] => Another 600 Template 
        [2] => Another 600 Template 
        ) 
)

insert.php页面仅插入扩展名和机密数据。不是手机或模板数据。电话和模板数据通过原始格式的下拉框进入阵列。这是我正在使用的代码

// Escape user inputs for security
$ext = mysqli_real_escape_string($link, $_POST['extension']);
$secret = mysqli_real_escape_string($link, $_POST['secret']);
$macaddress = mysqli_real_escape_string($link, $_POST['phone']);
$templatename = mysqli_real_escape_string($link, $_POST['template']);

// attempt insert query execution
$sql = "INSERT INTO assignments 
                (id, extension, secret, macaddress, template) 
        VALUES  (null,'$ext', '$secret', '$macaddress', '$templatename')";

if(mysqli_query($link, $sql)){
    echo "Records added successfully.";
} else{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}

// close connection
mysqli_close($link);
?> 

我哪里错了? 感谢

1 个答案:

答案 0 :(得分:0)

1)它们是数组,因此您需要在循环中处理它们

  

2)您的脚本存在SQL Injection Attack的风险   看看Little Bobby Tables偶然发生了什么   if you are escaping inputs, its not safe!   使用prepared parameterized statements

3)你不需要将NULL传递给id列,如果它的AutoIncrement,mysql会自动监视它

// attempt insert query execution
$sql = "INSERT INTO assignments 
                (extension, secret, macaddress, template) 
        VALUES  (?,?,?,?)";

$result = $link->prepare($sql);

foreach ($_POST['extension'] as $idx => $extention) {
    $result->bind_param('ssss',
                        $extension,
                        $_POST['secret'][$idx],
                        $_POST['phone'][$idx],
                        $_POST['template'][$idx]
                        );

    if( $result->execute() ) {
        echo "Records $idx added successfully.";
    } else{
        echo "ERROR: Could not execute $sql. " . $result->error;
        exit;
    }
}

// close connection
mysqli_close($link);
?>