0

I am stuck with this for hours, trying to fix it, but my little knowledge of php is not being enough, so I am asking for your help.

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 validate (separate file)

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')";

Error

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

It keeps telling me I am converting an array to string when I use implode, I have no idea what I am doing wrong, I just have several checkboxes, and the selected ones go to an array, then I implode that array to a string to be able to send it to the mysql database...

It is probably a stupid mistake, but I am fairly new to php and mysql, so... can anyone help me?

I wrote $type_string to $typestring, but the problem remains, the notice still happens...

3
  • 5
    $type_string != $typestring Commented Jun 23, 2014 at 14:38
  • 2
    replace array($_POST["type"]) by $_POST["type"] Commented Jun 23, 2014 at 14:39
  • what @JohnConde says $typestring should be $type_string or the other way around. Commented Jun 23, 2014 at 14:39

2 Answers 2

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

now contains an array with 0 => array

So the implode is still trying to convert key 0 to a string.

Either

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

Which is what i think you meant or

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

should fix it.

also make sure you defend against SQL injection

Sign up to request clarification or add additional context in comments.

2 Comments

FINALLY, so thank you really, such a simple fix to something I was stuck for hours! Literally hours, I should have asked this here earlier... Oh well, thank you a lot, really, completely fixed it :)
I am going to accept this answer as soon as it allows me (gotta wait 5min)
0

$POST["type"] is already array. In Your code You are creating array(array()) srtucture. If You want to be sure You are working with array use

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

or cast to array by using

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

then You are free to use implode Good luck :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.