October 16, 2012

explode and select each element from array

Question by user1694724

I have a small task where I have a mysql table “shops”.It contains a column “categories”. Each field of categories contains diiferent values like “22,44,33,55,24,33,22”
Now taking each value from that field, i need to get the value from a column “parent” in another table. (linking with ids) I am selecting the whole string, but i want to select each number. Please help me with this.

$db_selected = mysql_select_db("",$con);
$sql = "SELECT categories from shops";
$array = mysql_query($sql,$con);
while($row=mysql_fetch_array($array)){
foreach($row as $value){
    $result= explode(" ", $value);
    foreach($result as $newvalue){
    $query="SELECT parent FROM categories where categories.id=$newvalue<br/>";
    echo $query;
    }
    }
    }
mysql_close($con);
?>

Answer by Starx

You are exploding based on a space charater but your value needs to be exploded on the basis of ,. So try that

$result= explode(",", $value);
foreach($result as $newvalue){

    $query="SELECT parent FROM categories where categories.id='$newvalue'";
                                                           // ^ Quotes the Value
                                                           // Remove the <br />

    echo $query."<br />"; //Instead add it here and avoid the bug if you decide the run the query

    // This example is showing mysql_* library but it is deprecated

    $result = mysql_query($query);
    $row = mysql_fetch_assoc($result);
    $parent = $row['parent']; //Now you can something like this


}
...

Please fill the form - I will response as fast as I can!