如何在数据库中存储数组? [英] How to store a array in a database?

查看:261
本文介绍了如何在数据库中存储数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习 php 数据库,但我有一个问题.如何在数据库中存储数组?我在 stackoverflow 上看到了一个答案,他们用 double 类型做了一些事情,在另一个答案中,他们正在谈论为每个用户创建一个表,但我找不到解决方案.

I am trying to learn php databases and I have a question. How do I store an array in a database? I saw an answer on stackoverflow and there were they doing something with type double and in an other answer they were talking about creating a table for every user but I can't find a solution.

总结一下.我想在数据库中存储一个数组.我可以访问 phpmyadmin,所以我可以从那里设置值类型.我想将该数组存储在一列中.

So summarized. I want to store an array in a database. I have acces to phpmyadmin so from there can I set the value type. and I would like to store that array in one column.

有人可以帮我解决问题吗?

Can somebody help me solving the problem?

编辑一:我要存储的东西是音乐标签.所以在代码中它会是这样的:

edit one: The things I want to store are music tags. So in code it would be something like this:

 array('pop','rock','country');

我想将它存储在一列中以便于搜索

I want to store It in one column to make it easy searchable

推荐答案

通常您不应该将数组存储在 db 的单个列中.最好有一个带有标签的表格,另一个将您的实体与其标签链接起来.因此,在尝试将数组存储在表中之前,只需考虑在您的特定情况下这样做是否真的正确(通常不是).

Usually you shouldn't store arrays in a single column in a db. It is preferable to have a table with tags and another one that links your entity with its tags. So, before try to store an array in a table just think if it is really the right thing to do in your specific case (usually not).

如果您确定要这样做,那么您可以使用 serializeunserialize 函数.

If you are sure you want to do that then you have serialize and unserialize functions.

更新(五年后)serializeunserialize 方法本质上是不安全的,应该避免.最好使用 json_encodejson_decodeJSON 格式存储数据.

UPDATE (after five years) serialize and unserialize methods are inherently unsecure and should be avoided. It is preferable to store data in JSON format using json_encode and json_decode.

这篇关于如何在数据库中存储数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆