karthik
karthik

Reputation: 110

how to store array values into single cell in mysql table using php?

My question is how to store string or integer array values into mysql table. inside a table all values are store into single cell, the values are separated by comma.

ex:

<input type="text" name="product[]" value="rose">
<input type="text" name="product[]" value="garlands">
<input type="text" name="product[]" value="marigold">
<input type="text" name="product[]" value="jasmine">
<input type="text" name="product[]" value="jasmine garlands">

The above values are inserted into mysql table

$sql=mysql_query(" insert into product_sale(product_name) values (?)");

how to store all values and separated by comma, the stored values like

(rose,garlands,marigold,jasmine,jasmine garlands) in a single cell.

Upvotes: 0

Views: 2954

Answers (3)

karthik
karthik

Reputation: 110

<?php
include 'connection/db_connection.php';
if(isset($_REQUEST['save'])) {
$product_name = implode(",", $_REQUEST["product"]);
print $product_name;
}
$query="insert into product (product_name) values('".$product_name."')";
$sql=mysql_query($query);
if($sql) 
echo "success";
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<form name="myform" method="post">
<input type="text" name="product[]" value="rose">
<input type="text" name="product[]" value="garlands">
<input type="text" name="product[]" value="marigold">
<input type="text" name="product[]" value="jasmine">
<input type="text" name="product[]" value="jasmine garlands">
<input type="submit" name="save" value="Save">
</form>

</body>
</html>

Upvotes: 0

Leandro Papasidero
Leandro Papasidero

Reputation: 3738

This is just a demo. Then, you can bind $product_name into your insert query.

<?php
if(isset($_REQUEST['save'])) {
    $product_name = implode(",", $_REQUEST["product"]);
    print $product_name;

}
$query="insert into product (product_name) values('".$product_name."')";
$sql=mysql_query($query);
if($sql)
    echo "success";
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<form name="myform" method="post">
    <input type="text" name="product[]" value="rose">
    <input type="text" name="product[]" value="garlands">
    <input type="text" name="product[]" value="marigold">
    <input type="text" name="product[]" value="jasmine">
    <input type="text" name="product[]" value="jasmine garlands">
    <input type="submit" name="save" value="Save">
</form>

</body>
</html>

Upvotes: 2

Nishant Solanki
Nishant Solanki

Reputation: 2128

comma separated values in a single table cell is not a good practice, Do take an another table with fields id and product_id,

if you want to fetch this data than it will be easy to fetch and display, comma separated values will be very messy

Upvotes: 0

Related Questions