0

I am storing the IDs of names with implode() function and comma separated like 1,3. Column name is diet_id(varchar) and it has values 1,3. Now i want to fetch and display these IDs and their names like ID1 is ABC and ID2 is XYZ. I am using explode function to fetch and display but it returns me Array. Here is what i did so far

Fetching

<?php
$ShowProducts = mysqli_query($con, "SELECT * FROM food WHERE merchant_id='$userId'");
while($row=mysqli_fetch_assoc($ShowProducts)){
// Getting Names from IDs
$Diet_query     = mysqli_query($con,"SELECT * FROM diets WHERE id=".$row['diet_id']);
$main_diet      = mysqli_fetch_assoc($Diet_query);
$ar = explode(' ',$main_diet); 
?>

Now displaying

<td><?php echo $ar;?></td>

but it returns me Array

2
  • If you store them with a Comma, you should also explode them with a Comma :) Commented Feb 18, 2021 at 23:17
  • 1
    explode() takes a string and returns it as an array of pieces. What did you expect? Commented Feb 18, 2021 at 23:30

2 Answers 2

1

explode() always returns an array. In your example the single values are 1 and 3 (exploded from 1,3). Therefore the array will have two fields. One with the value 1 and one with the value 3.

The text "Array" is the standard string representation of an array in PHP. If you want to print out the values individually you can use their indexes (starting with 0):

<td><?php echo $ar[0];?></td>
<td><?php echo $ar[1];?></td>

There also many many other ways how to display array data, also see this question for reference.

Side note: In your post you are exploding the values by space and not by comma, so you might want to change your call to the explode() function accordingly if the value is actually stored with a comma as you said:

$ar = explode(' ',$main_diet); 

should be:

$ar = explode(',',$main_diet); 
Sign up to request clarification or add additional context in comments.

Comments

0

I checked my above query with var_dump(), it was bringing no data. When entry is only 1 in the table like 5, then it was showing data but with 3.5.2, it was showing null. changed my query to this

$sql = "SELECT * FROM food";
$result = mysqli_query($con, $sql);
$row = mysqli_fetch_assoc($result);
$ids = $row["diet_id"];
$sql = "SELECT * FROM diets WHERE id IN ($ids)";
$result = mysqli_query($con, $sql);
while ($drow = mysqli_fetch_assoc($result))
{
$diet_name[] = $drow['diet_full_name'];
}

and then

<td><?php echo implode(", ", $diet_name);?></td>

It worked then

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.