0

Do you have to use a loop to extract the value from a query array.

Query:

$fetchRegion = Singlequery("SELECT region FROM regions WHERE id = :id LIMIT 1",
                           array('id' => $_GET['region']),
                           $conn);

This is my array:

array(1) {
  [0]=>
  array(1) {
    ["region"]=>
    string(10) "South West"
  }
}

I want to take the value and use it in another query, I didn't know if I had to use a foreach for example to get the value to use in my next query. The other stackoverflow questions that I saw used a loop

1
  • Rather than take that value and use it in another query, consider using a single query with a JOIN: What's the query that you want to use it in? Commented Jan 26, 2015 at 11:48

4 Answers 4

1

If i understand your question correctly and you want to acces to value then access it like so:

$fetchRegion[0]['region'];

You don't need to use foreach or any other loop since it will return at most one element because LIMIT 1 you used in query.

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

2 Comments

Can I use this to get a string and store it in another variable so for example $region = 'string from array';
Yes, you can ex. $region = $fetchRegion[0]['region'];
1

Using loop :-

foreach($fetchRegion as $v) {
  $var = $v["region"];
}

or you get directly like:-

echo $fetchRegion[0]["region"];

Comments

0

No, there is no need to use a loop with that query because it will not return more than a single row. Instead, just check that you got a row back (it could return no results), and then use it.

Comments

0

If you're certain that your result is going to look like that, reset(reset($fetchRegion)) will give you the value 'south west'. It will behave badly if you don't get that exact format back though - for example, if the query does not return a row.

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.