spfoonnewb Posted March 24, 2007 Share Posted March 24, 2007 Hi, I have a value in a database that looks like "2, 5, 6, 1, 3" I want PHP to take that, and split it for each number, then check a different table and display the name for that number. Heres what I had so far, but it only displays one row.. So if in the database the user selected "2, 5, 6, 1, 3" I would want it to search a database for ID names corresponding to the ID So ID =1 Name=Test name 1 ID =2 Name=Test name 2 I want PHP to return Test name 2, Test name 5.. etc All of the below is also in a while statement, so that it does it for each user. <?php $pieces = explode(",", $row["val"]); foreach ($pieces as $value) { $r = mysql_query("SELECT name FROM tb2 WHERE id = '$value'") or die(mysql_error()); while($row = mysql_fetch_array( $r )) { echo $row["name_ofid"]; } } ?> Link to comment https://forums.phpfreaks.com/topic/44066-solved-foreach-help/ Share on other sites More sharing options...
Psycho Posted March 24, 2007 Share Posted March 24, 2007 You are making it more complex than it needs to be. YOu can simply query all the records in one shot since you have the list comma separated: <?php $query = "SELECT name FROM tb2 WHERE id IN ($row['val'])"; $result = mysql_query($query) or die (mysql_error()); while($row = mysql_fetch_array($result)) { echo $row['name']; } > Link to comment https://forums.phpfreaks.com/topic/44066-solved-foreach-help/#findComment-214006 Share on other sites More sharing options...
spfoonnewb Posted March 24, 2007 Author Share Posted March 24, 2007 That worked.. needed to fix syntax though. Thanks $query = "SELECT name FROM tb2 WHERE id IN (".$row["val"].")"; Link to comment https://forums.phpfreaks.com/topic/44066-solved-foreach-help/#findComment-214010 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.