1

My if statements are only adding one element to the arrays even though they should add several as several have identical tags.

<?php

include("mysqlconnect.php");

$select_query = "SELECT `ImagesId`,`ImagesPath`,`Tag` FROM `offerstbl` ORDER by `ImagesId` DESC";
$sql = mysql_query($select_query) or die(mysql_error());   

$data = array();

while($rows = mysql_fetch_array($sql,MYSQL_BOTH)){
    if ($rows['Tag'] == "sport"){
      $data['sport'] = array($rows['ImagesId'], $rows['ImagesPath'], $rows['Tag']);
    }
    if ($rows['Tag'] == "food"){
      $data['food'] = array($rows['ImagesId'], $rows['ImagesPath'], $rows['Tag']);
    }
   if ($rows['Tag'] == "clothes"){
      $data['clothes'] = array($rows['ImagesId'], $rows['ImagesPath'], $rows['Tag']);
    }
}

 echo json_encode($data);


 ?>
2
  • switch, case, break to make it neater perhaps? Commented Aug 28, 2014 at 0:33
  • You don't need $data = array();, but that won't matter. What do you mean one element, one element as in one array? Please make clear. I'm guessing you need to do this: $data[]['sport'] = . You probably need a multidimensional array. Commented Aug 28, 2014 at 0:37

2 Answers 2

1

You're overwriting the array element instead of pushing a new element onto the array. It should be:

$data['sport'][] = array($rows['ImagesId'], $rows['ImagesPath'], $rows['Tag']);

Also, your if seems unnecessary, since the keys of $data are identical to the tags. Just do:

$data[$rows['Tag']][] = array($rows['ImagesId'], $rows['ImagesPath'], $rows['Tag']);

I also recommend using associative arrays for the elements that you're adding, not indexed arrays:

$data[$rows['Tag']][] = array('ImagesId' => $rows['ImagesId'], 
                              'ImagesPath' => $rows['ImagesPath'], 
                              'Tag' => $rows['Tag']);

And since these keys are the same as the keys in $rows, you can simplify it to:

$data[$rows['Tag']][] = $rows;

You should also use MYSQL_ASSOC rather than MYSQL_BOTH, since you're never accessing the numeric keys of $rows.

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

Comments

0

You must change three lines from your code

$data['sport'] = array($rows['ImagesId'], $rows['ImagesPath'], $rows['Tag']);

to

$data['sport'][] = array($rows['ImagesId'], $rows['ImagesPath'], $rows['Tag']);

This

$data['food'] = array($rows['ImagesId'], $rows['ImagesPath'], $rows['Tag']);

to

$data['food'][] = array($rows['ImagesId'], $rows['ImagesPath'], $rows['Tag']);

This

$data['clothes'] = array($rows['ImagesId'], $rows['ImagesPath'], $rows['Tag']);

to

$data['clothes'][] = array($rows['ImagesId'], $rows['ImagesPath'], $rows['Tag']);

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.