0

The array it is fetching has size 2 , so if we comment out $size it returns 2 , but the for loop prints only the value present at 0th position of table column and not the next at 2th giving the error:

Undefined offset: 1

Code:

$allunstitched="Select p_id from unstitchedproduct";
$resultAllUnstitched= mysqli_query($connection,$allunstitched);
$AllUnstitchedResult= mysqli_fetch_array($resultAllUnstitched);
//$size=count($AllUnstitchedResult);

for ($i=0, $count = count($AllUnstitchedResult); $i < $count; ++$i) {
  print $AllUnstitchedResult[$i];
}

3 Answers 3

1

You're using mysqli_fetch_array. This function returns the result twice by default: indexed both by number and by column name. Here the result set has only one column, so you get its value twice in the array: first with index 0 and then with a string index. There is no index 1.

To get the results with numerical indexes only, pass MYSQLI_NUM as a second argument to mysqli_fetch_array:

mysqli_fetch_array($resultAllUnstitched, MYSQLI_NUM);
Sign up to request clarification or add additional context in comments.

Comments

0

Um, i dont think you have a problem in your for-loop; since your query reads ONE field/column it should have 1 iteration (=0 index), so the =1 undefined is correct (in my opinion).

What you should do is a loop that calls repeatedly mysqli_fetch_array to get all rows, like this:

while($AllUnstitchedResult = mysqli_fetch_array($resultAllUnstitched,MYSQLI_NUM)) {
   foreach ($AllUnstitchedResult as $field) {
      print $field;
   }
}

Comments

0

If you start at 0, if count = 5 you'll have 6 elements (0,1,2,3,4,5), beware of that. You need to loop (count-1) times:

 $count = count($AllUnstitchedResult);
 for ($i=0, $i < $count-1; $i++) {
    print $AllUnstitchedResult[$i];
 }

2 Comments

Right now I have 2 values in the database , so count is 2 and $i=0 ,so the loop is ok !
This way you don't process the last item in the array.

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.