Implode()使数组到字符串不起作用


Implode() to make an array to string not working?

我被这个问题困扰了几个小时,试图解决它,但我对php的了解还不够,所以我请求你的帮助。

HTML

        <input type="checkbox" name="type[]" value="type1">Type 1<br>
        <input type="checkbox" name="type[]" value="type2">Type 2<br>
        <input type="checkbox" name="type[]" value="type3">Type 3<br>
        <input type="checkbox" name="type[]" value="type4">Type 4

PHP验证(单独的文件(

if (empty($_POST["type"])) {
    $typeErr = "This field is required";
} else {
    $type = array($_POST["type"]);
}

PHP

/*this is line 90*/ $type_string = implode(',', $type);
$sql = "INSERT INTO `table1`(`type`) VALUES ('$type_string')";

错误

 Notice: Array to string conversion in C:'xampp'htdocs'project'example.php on line 90

它一直告诉我,当我使用内爆时,我正在将数组转换为字符串,我不知道自己做错了什么,我只有几个复选框,选中的复选框会转到一个数组,然后我将该数组内爆为字符串,以便能够将其发送到mysql数据库。。。

这可能是一个愚蠢的错误,但我对php和mysql还很陌生,所以……有人能帮我吗?

我将$type_string写入$typestring,但问题仍然存在,通知仍然发生。。。

$type = array($_POST["type"]);

现在包含一个具有0 => array 的阵列

所以内爆仍然试图将键0转换为字符串。

任一

$type = (array) $_POST["type"]; 

我想你的意思是

 /*this is line 90*/ $type_string = implode(',', $type[0]);

应该修复它。

还要确保您能够抵御SQL注入

$POST["type"]已经是数组。在您的代码中,您正在创建数组(array(((结构。如果你想确定你正在使用阵列使用

if(is_array($_POST["type"])){ $type=$_POST["type"] }

或使用投射到阵列

$type = (array)$_POST["type"];

那么你可以自由使用内爆祝你好运:(