How to store an array into mysql?

PhpMysqlDatabase

Php Problem Overview


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?

Php Solutions


Solution 1 - Php

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.

Solution 2 - Php

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

You can then unserialize the array when needed.

Solution 3 - Php

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.

Solution 4 - Php

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 :)

Solution 5 - Php

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.

Solution 6 - Php

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

Solution 7 - Php

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!

Solution 8 - Php

You can use the php serialize function to store array in MySQL.

<?php
 
$array = array("Name"=>"Shubham","Age"=>"17","website"=>"http://mycodingtricks.com");
 
$string_array = serialize($array);
 
echo $string_array;
 
?>

It’s output will be :

a:3{s:4:"Name";s:7:"Shubham";s:3:"Age";s:2:"17";s:7:"website";s:25:"http://mycodingtricks.com";}

And then you can use the php unserialize function to decode the data.

I think you should visit [this page on storing array in mysql][1].

[1]: https://web.archive.org/web/20160730213347/mycodingtricks.com/php/store-array-in-mysql/ "store array in mysql"

Solution 9 - Php

You can save your array as a json.
there is documentation for json data type: https://dev.mysql.com/doc/refman/5.7/en/json.html

Solution 10 - Php

Storing with json or serialized array is the best solution for now. With some situations (trimming " ' characters) json might be getting trouble but serialize should be great choice.

Note: If you change serialized data manually, you need to be careful about character count.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKing JulienView Question on Stackoverflow
Solution 1 - PhpDaniel VassalloView Answer on Stackoverflow
Solution 2 - PhpGrant CollinsView Answer on Stackoverflow
Solution 3 - PhpPekkaView Answer on Stackoverflow
Solution 4 - PhpDennis HaarbrinkView Answer on Stackoverflow
Solution 5 - PhpBjörnView Answer on Stackoverflow
Solution 6 - PhpSrinivas Reddy ThatiparthyView Answer on Stackoverflow
Solution 7 - PhpHardline_98View Answer on Stackoverflow
Solution 8 - PhpShubham KumarView Answer on Stackoverflow
Solution 9 - PhpRoberto MurguiaView Answer on Stackoverflow
Solution 10 - PhpBŭnyãmin AkçãyView Answer on Stackoverflow