Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Gard Mikael Fjeldavli
19,416 PointsPHP AND MySQL querys
Okay, so this is the var_dump from the query ("SELECT * FROM user_devices WHERE user_id = 1" ) with fetchAll in php.
Question 1: It looks like every element/row in the db table has 6 values, even though it really only has 3; namely "id", "user_id" and "device_nr". My guess is that u should be able to access theese both with the column name and the column index. Is this the case?
Question 2: Lets say I store this array in a variable called $devices. How do I access the value "device_nr" from lets say the second element(102). How do I target that?
array(3) {
[0]=>
array(6) {
["id"]=>
string(1) "1"
[0]=>
string(1) "1"
["user_id"]=>
string(1) "1"
[1]=>
string(1) "1"
["device_nr"]=>
string(3) "101"
[2]=>
string(3) "101"
}
[1]=>
array(6) {
["id"]=>
string(1) "2"
[0]=>
string(1) "2"
["user_id"]=>
string(1) "1"
[1]=>
string(1) "1"
["device_nr"]=>
string(3) "102"
[2]=>
string(3) "102"
}
[2]=>
array(6) {
["id"]=>
string(1) "3"
[0]=>
string(1) "3"
["user_id"]=>
string(1) "1"
[1]=>
string(1) "1"
["device_nr"]=>
string(3) "103"
[2]=>
string(3) "103"
}
}
1 Answer
Shawn Gregory
Courses Plus Student 40,672 PointsHello,
It looks like the function you used to grab the information from the database (FetchAll I believe) is,indeed, returning the 3 columns in your database. However, how the function is returning the data is two ways: where the value is indexed with the keys 0-2 as well as the names of the columns in your database. That way what ever array you put your return query in, let's day $result, can either be referenced either by: $result[0] or $result['id']. Some functions do it that way to allow people who prefer to deal with the numbered array keys as well as those who prefer the named array keys. If you take a look at the var_dump information you can see that you are returning a duplicate of 3 pieces of information: one set in numbered keys and the other in named keys. Hope this helps.
Cheers!