chrscote Posted February 5, 2015 Share Posted February 5, 2015 I am writing a small page in which I want a combo box giving a list of options taken from a database table where the ID from the table is the value and the string is the actual option. I am trying to set it up using a foreach statement, but I keep getting the following error message: Notice: Array to string conversion in issue.php on Line 87. Here is the code I'm using to create this array. First, this is in the beginning of the file to get the array: $sqlStatuses = "SELECT StatusID, Status FROM Status"; try { $rsStatuses = $db->query($sqlStatuses); $arrAllStatus = $rsStatuses->fetchAll(); } catch (Exception $e) { echo $e->getMessage(); } Then in the page body, I am using: <select id="status"> <?php foreach ($arrAllStatus as $statID=>$status) { echo "<option value=\"$statID\"$selected>$status</option>"; } ?> </select> The errors I am getting are on the echo line. Do the variables I use after the "as" have to be the same as the fields in the table? I didn't think so. Chris Quote Link to comment https://forums.phpfreaks.com/topic/294414-trouble-using-foreach-with-associative-array/ Share on other sites More sharing options...
Solution mac_gyver Posted February 5, 2015 Solution Share Posted February 5, 2015 the ->fetchAll() method returns an array of arrays. in your foreach() loop, $status is an array holding the data for each row. $statID will just be the zero referenced numerical array indexes of the main array. using foreach ($arrAllStatus as $row) { would perhaps be clearer. you would then reference the two columns you have selected using - $row['StatusID'] and $row['Status'] Quote Link to comment https://forums.phpfreaks.com/topic/294414-trouble-using-foreach-with-associative-array/#findComment-1504995 Share on other sites More sharing options...
chrscote Posted February 5, 2015 Author Share Posted February 5, 2015 Thank you very much for your help! Quote Link to comment https://forums.phpfreaks.com/topic/294414-trouble-using-foreach-with-associative-array/#findComment-1504998 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.