0

I have stored multiple products in database column like (1,3,5). Now i want to get the names of these products and display them from products table.

I am not getting how to do it.

I am saving like this

if(is_array($_POST['products'])){
   $products = implode(',', $_POST['products']);
} else {
   $products = $_POST['products'];
}

how to check do this, please suggest. I tried using in_array, but it didn't work

user2823107
  • 99
  • 2
  • 12

1 Answers1

0

Get your products from the database, then use PHP's explode():

$products = explode(',', $productsFromDatabase);

See: http://php.net/explode

This will give you an array again. With the array, depending on what you've stored, you can just use these values to look up individual products.

foreach ($products as $values) {
  // SELECT SQL statement here using a WHERE clause depending on what value you stored.
  // Ex: SELECT * FROM `products` WHERE id='$value'
  // Ex: SELECT * FROM `products` WHERE name='$value'
}

Assuming you're getting product names from IDs, you can utilize the foreach loop to populate an array that you can then implode for a list of product names:

$names = array();
foreach ($products as $values) {
  // SELECT SQL statement here using a WHERE clause depending on what value you stored.
  // Ex: SELECT * FROM `products` WHERE id='$value'
  // Ex: SELECT * FROM `products` WHERE name='$value'

  // Assume you have attained a $row using a select statement
  $names[] = $row['name'];
}

$names = implode(',', $names);
echo $names;

This can be simplified greatly if you simply store product names instead of IDs, however I recognize that the IDs may have practical uses in other parts of your code.

Meetarp
  • 2,331
  • 1
  • 23
  • 31
  • Thanks, It displays the name but it displays continuosly, i want , after each product. I tried like this `echo rtrim(implode(',', $s2['name']), ',');`, but blank – user2823107 Dec 17 '14 at 18:05
  • Is `$s2` a row you fetched from the database? If it is, take a look at my edited response. – Meetarp Dec 17 '14 at 18:15
  • This Worked!!! Thank you very much. I have used ID as there are many tables , when i update 1 place everything will b updated according to that id. Thanks a Ton – user2823107 Dec 17 '14 at 18:29