Jump to content

Mysql query from array values


dk4210

Recommended Posts

Hello Guys,

 

I have a question

 

I have the following query

 

$result3 = mysql_query("SELECT * FROM table1 WHERE ad_id='$id2'")
or die(mysql_error());  


$row3 = mysql_fetch_array( $result3 );

// Grab all the var
$features = $row3['features'];

 

I am turning it into an array (comma separated)

 

$feature2 = explode(",", $features);
print_r($feature2);

)

 

The result is like so

 

Array ( [0] => 5 [1] => 9 [2] => 13

 

 

I want to query the features for just the ids (F_name) are for the features . This query will show all.. I would like to just display the f_name values from the array query.

 

// build and execute the query
$sql = "SELECT * FROM features";
$result = mysql_query($sql);

// iterate through the results
while ($row = mysql_fetch_array($result))
{
  echo $row['f_name'];
  echo "<br />";
}

 

Please Advise..

 

Thanks, Dan

Link to comment
https://forums.phpfreaks.com/topic/255423-mysql-query-from-array-values/
Share on other sites

While the suggested method is OK, the specific syntax is not - http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#function_in

 

The IN() comparison takes a comma separate list of numbers (or strings), not an array.

that was the point of turning the array into a comma separate list of numbers

as in

 

$feature2 = explode(",",$feature2);

 

it got lost out of the "code" box, but it's there in my post

 

so you get

$feature2 = explode(",",$feature2);
$sql = "SELECT * FROM features WHERE f_id  IN $feature2";

 

which is using a comma separate list of numbers, as is needed, not an array

 

sorry i messed the code box up, hopefully it's clear now

 

 

 

 

actually looking at it again there's no need for the array bit,

and i completely b'd that up anyway cause explode isn't what's needed

 

double sorry  8)

 

$features is a comma seperated list anyway, like (1,5,9)

 

$sql = "SELECT * FROM features WHERE f_id  IN $features";

 

should work

I'd say that your DB is not 'normalized'. You keep a list of features in one field. But you'd better keep it in different rows. Maybe you need one more table...

 

Read about it, for example, here http://en.wikipedia.org/wiki/Database_normalization

FYI - This is what I used to fix my issue

 

$feature2 = explode(",", $features);

$feature3 = implode(',', $feature2);

// First Query to grab Feature1
$result = mysql_query("SELECT * FROM features WHERE f_id IN ( $feature3 )
") or die("Sql error : " . mysql_error());

while($row = mysql_fetch_assoc ($result)){
    $f_name=$row["f_name"];
    echo "<br>".$f_name;
    }

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.