Forum Moderators: open

Message Too Old, No Replies

"VLOOKUP" on mySQL

         

wigglyworm91

2:06 am on Oct 7, 2008 (gmt 0)

10+ Year Member



You know the xls function VLOOKUP? is there an equivalent for that on mysql? i.e.

<?
(connect, etc.)
mysql_query(SELECT Name FROM 'Members' WHERE 'ID#'=$ID)
?>
...and then somehow print the result-set...how that works, i don't know. Thanks.

dougmcc1

3:25 am on Oct 9, 2008 (gmt 0)

10+ Year Member



I use nested while loops. Run a query to select all the values from your initial list, and within that loop select all the values in your second list where a value from your initial list is found.

dougmcc1

3:35 am on Oct 9, 2008 (gmt 0)

10+ Year Member



Rough PHP code (not tested):


$query="select state from states";
$result=mysql_query($query);
while($row=mysql_fetch_assoc($result)) {
extract($row); //turns state into a variable $state

$query2="select city from cities where state='$state'";
$result2=mysql_query($query2);
while($row=mysql_fetch_assoc($result2) {
extract($row2);
echo "$city, $state<BR>";
} //end of city while loop
} //end of state while loop

There might be a way to use a subquery which would be faster and require far less code but would be more restrictive. Depends on the output you need.

coopster

2:08 pm on Oct 10, 2008 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



MySQL has a FIND_IN_SET function that may work for you. There are a few examples and example thread links listed in these past discussions:

[webmasterworld.com...]
[webmasterworld.com...]

or you may be able to use a CASE structure of sorts, something along these lines

[webmasterworld.com...]