Display names of stored array IDs
I have saved multiple products in a database column like (1,3,5). Now I want to get the names of these products and display them from the products table.
I don't understand how to do this.
I save this as
if(is_array($_POST['products'])){
$products = implode(',', $_POST['products']);
} else {
$products = $_POST['products'];
}
how to check it please suggest. I tried to use in_array
but it didn't work
source to share
Get your products from the database, then use PHP explode()
:
$products = explode(',', $productsFromDatabase);
This will give you an array again. With an array, depending on what you saved, you can simply use these values ββto find 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 are getting product names from IDs, you can use a foreach loop to populate an array, which you can then unbind 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 greatly simplified if you just store product names instead of IDs, however I understand that IDs can have practical uses in other parts of your code.
source to share