Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Notice: Undefined Offset : 2 How to Solve?

Tags:

php

I am having undefined offset:2 errors at Line 11 and 12. This is the code from Line 6 - 15.

    if(isset($_POST['submit'])){

        $surveyID =$_POST['surveyCategory'];

        for($i=0; $i<count($_POST['id']); $i++){
            $questionID = $_POST['id'][$surveyID][$i];
            $answer = mysql_real_escape_string(htmlspecialchars($_POST['answer'][$surveyID][$i]));
            mysql_query("INSERT INTO answers(survey_id, question_id, answer_body) VALUES   ('$surveyID', '$questionID', '$answer')") or die (mysql_error());
        }
    }
like image 363
user3103739 Avatar asked Dec 16 '13 08:12

user3103739


2 Answers

undefined offset means that an array have ran out of bounds.
Ie, the array size is smaller than the index that you are trying to fetch an object from.

From looking at your code, I would guess that its either the $surveyID that is higher than the array size ($_POST['id'] array) or the $id that is ($_POST['id'][$surveyID] array).
Are both of those arrays actually arrays?

You seem to iterate on the $_POST['id'] array size, but you try to get the object from the $_POST['id'][$surveyID] array, this could be a issue, cause you never check the size of that array.
You probably want to iterate with: $_POST['id'][$i] or check the size of the array $_POST['id'][$surveyID] in the loop instead (would guess the later).

I would recommend checking so that the $_POST['id'] array have the $surveyID key set too (and the type you expect it to be), cause the POST parameter could be pretty much anything at all (client have full control over the post params, they can send any value they want to your script with those).

edit
While I'm at it: Always validate/escape your Request parameters (in this case POST) before inserting them into a database.
You are currently using Mysql_* which is Deprecated (will be removed from php) and it could be a good idea to go over to either mysqli or PDO.
Both PDO and mysqli have Prepared statements, which helps a lot with escaping data (or at least see to that data inserted to database does not do bad things with it, like sql-injections).
So please, take a look at those (check the php.net docs)!

like image 71
Jite Avatar answered Sep 25 '22 23:09

Jite


You are counting $_POST['id'], but iterating over $_POST['id'][$surveyID].

Change to $i < count($_POST['id'][$surveyID])

like image 37
Niet the Dark Absol Avatar answered Sep 25 '22 23:09

Niet the Dark Absol