开发者

Insert an array in MySQL database

开发者 https://www.devze.com 2023-03-17 16:58 出处:网络
I want to insert an 开发者_如何转开发array into my MySQL database in the format a,b,c. `var_dump($pvt_contacts)`

I want to insert an 开发者_如何转开发array into my MySQL database in the format a,b,c.

 `var_dump($pvt_contacts)`

results

array(1) { [0]=> array(2) { [0]=> string(3) "102" [1]=> string(1) "3" } } 

I tried

`implode(',',$pvt_contacts)' 

but it echos Array not 102,3 as I expected . Please help me


If you just want 102,3, then you're off by one (your pointing to a parent array, and not the elements):

implode(',',$pvt_contacts[0]);
  • If you're trying to store an array in a DB, I recommend serialize. (despite its prevalence in Drupal, ExpressionEngine, Wordpress, etc. this is not generally the best idea).
  • If you're trying to sent an array to js, I recommend json_encode.
  • If you're doing something else I need more information.


It is suggested to use multiple rows to store the data, instead of storing the whole array into it. If you insist, here is the way:

Convert your array to the following format:

[key1]{value1}#[key2]{value2}#.... etc

You can use explode to convert it back to array.


The easiest way should be either serialize() or var_export(). But you should only use those if you do not intend to use the data inside the database in any way. If you want to run e.g. SELECT queries on this array data you should store it in a normalized way.


You should use serialize(), unserialize() or json_encode() , json_decode()

That would make it easier for you to write , and retreive back original data without the need of parsing your stored data yourself . Here are some good links to assist you :

Preferred method to store PHP arrays (json_encode vs serialize)

http://php.net/manual/en/function.json-encode.php

http://php.net/manual/en/function.serialize.php


You can implode your array into a string then explode it back. Default separator is the ,. If you want to run SELECT queries then you can use the MySQL-specific FIND_IN_SET() function however this whole scenario is not recommened, you should use a normalized way as others suggested above.


One way is to convert array to JSON. It will convert array to string and you will be able to store it.

  • json_encode,
  • json_decode;

Anyway, I don't think that this it the right way how to deal with the problem. Say, for example, you would need to store blog entries and tags for them into database.

How you do it know?

Save blog entry and tag into one table, one row. You convert all entries tags and save all into database.

How you should do it?

Make two tables:

  • entries,
  • entry_tags;

All info that's related to entry save into entries. For example: title, description. All tags save into entry_tags. In that table there are id (primary key), entry_id (ID that have relationships with entries ID) and tag that simply holds the name.

I hope this will help you!

0

精彩评论

暂无评论...
验证码 换一张
取 消