Some Java Guy
Some Java Guy

Reputation: 5118

json_encode(array) insertion in db

My array has some values

  0 => '1'
  1 => 'moisturizer'
  2 => 'skincare'

I am trying to convert that array to string, I am currently using json_encode

$value = array_shift( $val_ary ); //val_ary is that array
echo json_encode($value); // This will echo my data like

["1","moisturizer","skincare"]

later I would like to insert those values in my mysql db table

mysql_query("INSERT INTO TABLE (sno, type, category)
VALUES ('json_encode($value)')");

Should this work?

Or shall I json_decode before I insert in db?

Upvotes: 1

Views: 7351

Answers (3)

gen_Eric
gen_Eric

Reputation: 227310

JSON is a way to represent data as a string. It's used mainly to transport data.

JSON has no place here, just implode the data, and use it in the query.

mysql_query("INSERT INTO TABLE (sno, type, category) VALUES ".
    "(" . implode(",", $value) . ")");

Upvotes: 0

Kuf
Kuf

Reputation: 17846

json_encode(array) returns a json string, while values for MySQL insert should be (value1,value2,...). json_decode(json_string) return an array, and implode glues the arrays pieces with "," separating the array objects. There is no need to convert it to json if the only thing you do is to insert it to the DB. Usually json is being used for passing info between pages/servers (AJAX calls for example) or saving an array as a string in a DB

If you get the data as json:

$value = json_encode(array(value1,value2,...))

do

mysql_query("INSERT INTO TABLE (sno, type, category) 
    VALUES ('".implode(",",json_decode($value))."')");

if you get the data as array:

$value = array(value1,value2,...)

do

mysql_query("INSERT INTO TABLE (sno, type, category) 
    VALUES ('".implode(",",$value)."')");

Upvotes: 3

Muthu Kumaran
Muthu Kumaran

Reputation: 17930

I don't think you need JSON here. You can try do these,

$arr = array(0 => '1', 1 => 'moisturizer', 2 => 'skincare');
mysql_query("INSERT INTO TABLE (sno, type, category) VALUES ('{$arr[0]}', '{$arr[1]}', '{$arr[2]}')");

If your array is multidimensional then you can use foreach loop to insert the data,

$values = array();
foreach($arr as $k=>$v){
   $values[] = "('{$v[0]}', '{$v[1]}', '{$v[2]}')";
}
mysql_query("INSERT INTO TABLE (sno, type, category) VALUES ".implode(',', $values));

Note: Don't use mysql_* functions, they will be deprecated soon. Instead use PDO or MySqli functions.

Upvotes: 0

Related Questions