Jump to content

[SOLVED] foreach help


spfoonnewb

Recommended Posts

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

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.