Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store an array into mysql?

Is there a way to store an array into mysql field? I'm creating a comment rating system so I want to store the arrays of user ids to prevent multiple votings. I'm going to create new table that holds the comment id and the array of user ids who have voted on this comment. Than I'll join comments table and this table and check whether the current user id exists in the voters array or note. If it does than the voting icons would be disabled. I think I'll prevent to use mysql query in loop in this way.

Do you happen to know any better ways?

like image 445
King Julien Avatar asked Aug 05 '10 09:08

King Julien


People also ask

Can you store an array in a SQL database?

Conclusion. As you can see, SQL Server does not include arrays. But we can use table variables, temporary tables or the STRING_SPLIT function. However, the STRING_SPLIT function is new and can be used only on SQL Server 2016 or later versions.

Can you put array in database?

An array is a special variable that allows storing one or more values in a single variable e.g. – holding usernames or details in an Array. They are easier to manipulate. Sometimes, require to store Array in the MySQL database and retrieve it.

How do I find an array in MySQL?

We can retrieve the rows of the tables of a MySQL database in PHP language by using the mysql_fetch_array() function, mysqli_fetch_array() function or PDO_MYSQL driver in the form of arrays. These arrays can be either numeric arrays or associative arrays.

Can we store array in relational database?

SQL doesn't explicitly support arrays as a data type within its own language, but there are many workarounds to make it possible because it's a relational database. Relational databases like SQL work using relations and keys.


7 Answers

You may want to tackle this as follows:

CREATE TABLE comments (
    comment_id int, 
    body varchar(100), 
    PRIMARY KEY (comment_id)
);

CREATE TABLE users (
    user_id int, 
    username varchar(20), 
    PRIMARY KEY (user_id)
);

CREATE TABLE comments_votes (
    comment_id int, 
    user_id int, 
    vote_type int, 
    PRIMARY KEY (comment_id, user_id)
);

The composite primary key (comment_id, user_id) on the intersection table comments_votes will prevent users from voting multiple times on the same comments.

Let's insert some data in the above schema:

INSERT INTO comments VALUES (1, 'first comment');
INSERT INTO comments VALUES (2, 'second comment');
INSERT INTO comments VALUES (3, 'third comment');

INSERT INTO users VALUES (1, 'user_a');
INSERT INTO users VALUES (2, 'user_b');
INSERT INTO users VALUES (3, 'user_c');

Now let's add some votes for user 1:

INSERT INTO comments_votes VALUES (1, 1, 1);
INSERT INTO comments_votes VALUES (2, 1, 1);

The above means that user 1 gave a vote of type 1 on comments 1 and 2.

If the same user tries to vote again on one of those comments, the database will reject it:

INSERT INTO comments_votes VALUES (1, 1, 1);
ERROR 1062 (23000): Duplicate entry '1-1' for key 'PRIMARY'

If you will be using the InnoDB storage engine, it will also be wise to use foreign key constraints on the comment_id and user_id fields of the intersection table. However note that MyISAM, the default storage engine in MySQL, does not enforce foreign key constraints:

CREATE TABLE comments (
    comment_id int, 
    body varchar(100), 
    PRIMARY KEY (comment_id)
) ENGINE=INNODB;

CREATE TABLE users (
    user_id int, 
    username varchar(20), 
    PRIMARY KEY (user_id)
) ENGINE=INNODB;

CREATE TABLE comments_votes (
    comment_id int, 
    user_id int, 
    vote_type int, 
    PRIMARY KEY (comment_id, user_id),
    FOREIGN KEY (comment_id) REFERENCES comments (comment_id),
    FOREIGN KEY (user_id) REFERENCES users (user_id)
) ENGINE=INNODB;

These foreign keys guarantee that a row in comments_votes will never have a comment_id or user_id value that doesn't exist in the comments and users tables, respectively. Foreign keys aren't required to have a working relational database, but they are definitely essential to avoid broken relationships and orphan rows (ie. referential integrity).

In fact, referential integrity is something that would have been very difficult to enforce if you were to store serialized arrays into a single database field.

like image 186
Daniel Vassallo Avatar answered Oct 01 '22 12:10

Daniel Vassallo


You can always serialize the array and store that in the database.
PHP Serialize

You can then unserialize the array when needed.

like image 24
Grant Collins Avatar answered Oct 01 '22 13:10

Grant Collins


Consider normalizing the table structure into a comments, and a separate votes table.

Table "comments":

id
comment
user
...

Table "votes":

user_id  
comment_id
vote (downvote/upvote)

this would allow an unlimited number of votes without having to deal with the limits of a database field.

Also, you may have future needs for operations like "show all votes a user has cast", removing specific votes or limiting the maximum number of votes per day. These operations are dead easy and fast to implement with a normalized structure, and horribly slow and complex in a serialized array.

like image 37
Pekka Avatar answered Oct 01 '22 12:10

Pekka


create table like this,

CommentId    UserId
---------------------
   1            usr1
   1            usr2

In this way you can check whether the user posted the comments are not.. Apart from this there should be tables for Comments and Users with respective id's

like image 43
Srinivas Reddy Thatiparthy Avatar answered Oct 01 '22 12:10

Srinivas Reddy Thatiparthy


you should have three tables: users, comments and comment_users.

comment_users has just two fields: fk_user_id and fk_comment_id

That way you can keep your performance up to a maximum :)

like image 32
Dennis Haarbrink Avatar answered Oct 01 '22 11:10

Dennis Haarbrink


I'd prefer to normalize your table structure more, something like;

COMMENTS
-------
id (pk)
title
comment
userId


USERS
-----
id (pk)
name
email


COMMENT_VOTE
------------
commentId (pk)
userId (pk)
rating (float)

Now it's easier to maintain! And MySQL only accept one vote per user and comment.

like image 35
Björn Avatar answered Oct 01 '22 13:10

Björn


If you just store the data in a database as you would if you were manually putting it into an array

"INSERT INTO database_name.database_table (`array`)
    VALUES
    ('One,Two,Three,Four')";

Then when you are pulling from the database, use the explode() function

$sql = mysql_query("SELECT * FROM database_name.database_table");
$numrows = mysql_num_rows($sql);
if($numrows != 0){
    while($rows = mysql_fetch_assoc($sql)){
        $array_from_db = $rows['array'];
    }
}else{
    echo "No rows found!".mysql_error();
}
$array = explode(",",$array_from_db);
foreach($array as $varchar){
    echo $varchar."<br/>";
}

Like so!

like image 45
Hardline_98 Avatar answered Oct 01 '22 13:10

Hardline_98