0


I am having some trouble trying to get this done. The issue is:

I have an array that looks like

wants_arr_flat
(
[0] => booze
[1] => nudes
[2] => rooms

I want my foreach loop to go through these values making a different SQL statement and then saving the result of that SQL statement on to another array. The code I am trying to work with now is this.

    foreach ( $wants_arr_flat as $value ) {
      $sql = "SELECT * FROM offers WHERE user_id != $_SESSION[user_id] AND offer='$value'";
      $result=$conn->query($sql);
      $want_match_arr = mysqli_fetch_row($result);
    echo '<pre>'; print_r($want_match_arr); echo '</pre>';  //testing echo

Obviously this is just overwriting the last array each iteration so I only end up with one result in the array.

2
  • If you just need a list of all of the records, try $want_match_arr = mysqli_fetch_all($result); (php.net/manual/en/mysqli-result.fetch-all.php) Commented Jun 14, 2018 at 9:08
  • Btw I'm not sure you should make ONE request by loop. Try to build multiple query THEN after the foreach loop you make one request and you use mysqli_next_result() to get value from one select to the next :) Commented Jun 14, 2018 at 9:13

2 Answers 2

3

instead of

$want_match_arr = mysqli_fetch_row($result);

use

$want_match_arr[] = mysqli_fetch_row($result);
Sign up to request clarification or add additional context in comments.

1 Comment

would you mind accepting my answer as the right one? :)
0

If you get multiple rows from SQL then this is better.

$want_match_arr = [];
foreach ( $wants_arr_flat as $value ) {
  $sql = "SELECT * FROM offers WHERE user_id != $_SESSION[user_id] AND offer='$value'";
  $result=$conn->query($sql);
  while ($row = mysql_fetch_assoc($result)) {
     $want_match_arr[] = $row;
  }
}
echo '<pre>'; print_r($want_match_arr); echo '</pre>';  //testing echo

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.