lquidsilver Posted January 7, 2016 Share Posted January 7, 2016 Hey guys, As the title says I'm trying to get table data based on an array I have. Example: I have an array (array(1,2,3,4)), lets say that those values are IDs in a table. How would I go about getting the names from a table those values(IDs) are associated with? Thanks! Quote Link to comment https://forums.phpfreaks.com/topic/300218-fetching-table-info-based-on-array-values/ Share on other sites More sharing options...
mac_gyver Posted January 7, 2016 Share Posted January 7, 2016 (edited) implode the array into a list, with a comma as the separator character, then use that comma separated list in an IN() comparison in a WHERE clause in your query. ref: http://php.net/implode http://dev.mysql.com/doc/refman/5.7/en/comparison-operators.html#function_in are these values coming from external data and would need to be properly validated, cast, or put into a prepared query to prevent sql injection? Edited January 8, 2016 by mac_gyver Quote Link to comment https://forums.phpfreaks.com/topic/300218-fetching-table-info-based-on-array-values/#findComment-1529254 Share on other sites More sharing options...
benanamen Posted January 8, 2016 Share Posted January 8, 2016 Where is this array coming from? Quote Link to comment https://forums.phpfreaks.com/topic/300218-fetching-table-info-based-on-array-values/#findComment-1529258 Share on other sites More sharing options...
lquidsilver Posted January 8, 2016 Author Share Posted January 8, 2016 Awesome, that helped out immensely, thank you! How would I go about selecting the names individually based on the array number in the same situation? Example: Array(1,2,3,4) correspond with (Bob, Joe, Tom, Bill) in the table. How would I go about just selecting 2 and 4 in the array? In this example there could be 100+ id's in the array, but somewhere down the line I may just need the info from Bob and Tom Quote Link to comment https://forums.phpfreaks.com/topic/300218-fetching-table-info-based-on-array-values/#findComment-1529259 Share on other sites More sharing options...
akphidelt2007 Posted January 8, 2016 Share Posted January 8, 2016 (edited) Well array(1,2,3,4) is really array(0=>1,1=>2,2=>3,3=>4). And the names are array(0=>Bob,1=>Joe,2=>Tom,3=>Bill). There's multiple ways you can do this. You can use array_search to find the key based on id. But this is just based on the information you have given. There's probably easier ways to do what you are trying to do if we knew what you were actually doing and how you were doing it. Edited January 8, 2016 by akphidelt2007 Quote Link to comment https://forums.phpfreaks.com/topic/300218-fetching-table-info-based-on-array-values/#findComment-1529260 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.