Is it possible to save an array as a string in a MySQL database?

Is this considered a good practice?

I am planning to save bookmarks, with each bookmark being stored as a row in the table. I intend to have a tag column that will essentially be an array in string format holding the hierarchy of tags defining it. For instance:

url | tag
'stackoverflow.com', '[faves, internet, QandA]'

Below is my current table structure, and I am looking to make changes to the tag column to accommodate the array in string form.

https://i.sstatic.net/0IjMy.png

Answer №1

Avoid storing a comma-separated list in a string as it is generally not recommended.

However, if your queries consistently treat the entire string as a whole without the need for SQL expressions to search for individual elements, then there may be no harm in doing so.

In SQL, it is more efficient to consider each column as a single scalar value rather than an array. Treating a column as divisible sub-parts can complicate and slow down data processing.

When dealing with tags, it is advisable to have a one-to-many tag table where each bookmark can be associated with multiple tags, with one tag per row in the table.

Alternatively, you can use a lookup table for tags and then create a many-to-many table that maps bookmarks to their corresponding tags.

CREATE TABLE Tag (
  tag_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  tag VARCHAR(50) NOT NULL
);

CREATE TABLE BookmarkTag (
  bookmark_id INT NOT NULL,
  tag_id      INT NOT NULL,
  PRIMARY KEY (bookmark_id, tag_id),
  FOREIGN KEY (bookmark_id) REFERENCES Bookmark(bookmark_id),
  FOREIGN KEY (tag_id) REFERENCES Tag(tag_id)
);

This approach provides more flexibility:

  • No limit on the number of tags per bookmark
  • Simplified search for specific tags
  • Ease in calculating the number of tags per bookmark
  • Effective control over duplicates, allowed tags, removal of a specific tag from all bookmarks using it, etc.

For further insights, refer to my response to Is storing a delimited list in a database column really that bad?

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Neither setState() nor forceUpdate() trigger the rendering process

I am working with a basic React setup that resembles the following structure: index.js ReactDOM.render(<App />, document.getElementById('root')); App.js export default class App extends Component { constructor(props) { super ...

The insertMany method in Nodejs does not function properly with the Mongodb ordered option

I have integrated MongoDB into my application, specifically version 4.4.1. I made sure to set the unique option in the word field to true for data integrity. Here is the code snippet I am using: try { const words = [ { word: "her" }, ...

VueJS avoids displaying a specific data in every iteration of a v-for loop

Presented below is the code that I have managed to successfully get working: <span v-for="(item, index) in storedUserItems"> <template v-if="item.strength"> <img @mouseover="itemInfo(item, index)" style="padding: 5px;b ...

Anticipating the resolution of one promise before tackling the next in Angular.js

Is it possible in Angular.js to ensure that a given promise is resolved before another dependent promise? Consider the following code snippet: User.getAllUsers().then(function(users) { $scope.users = users; for (var i = 0; i < users.length; i+ ...

Exploring the functionality of Angular directives for bidirectional data binding with object references

In my custom Angular directive (v1.4.3), I am passing two bindings. The first binding is an Object with 2-way binding (model: '=') that can either be an Array or a single Object like [{something: 'foo'}, {something: 'moo'}, ...

PhantomJS fails to trigger function within page.evaluate

My current project involves scraping data from a Facebook page using the PhantomJS node module (https://github.com/sgentle/phantomjs-node). However, I am facing an issue where the function I pass to evaluate the page is not being executed. Interestingly, w ...

An unexpected column was found in the ON clause

When I try to combine information from 3 tables, I keep encountering an error that confuses me: ERROR 1054 (42S22): The database is showing "Unknown column 'orders_items.item_id' in 'on clause'" as the issue. This is the query I am us ...

Issue with Bootstrap alert persisting even after being displayed once

Having trouble with alert messages in jQuery where I display the message, validate data, and then try to hide it again. No errors in the console, even when logging before and after the process. SOLUTION $('#password, #confirm_password').on(& ...

The JSX function fails to display the return value

Having trouble getting the return value of a function to display on screen. The object words.First.wordsdata contains key-value pairs. import React from "react"; const WordList = ({ words }) => { return ( <div> ...

PHP PDO and MySql are used for creating a DataTable that can perform CRUD operations on the server

I am currently attempting to retrieve data from a child table using the ID stored in the child table. The goal is to populate a DataTable with records related to both the Parent and Child tables. Below you can find the code snippet: The issue arises when ...

Discovering the various combinations of endpoint parameters using Sequelize within Express.js

Exploring the potential of using Sequelize ORM in Express.js for querying a mySQL DB. In my Express.js setup, I've defined an endpoint that accepts two parameters 'level' and 'topic', as shown below: //Fetch Topic router.get("/tas ...

Instructions for creating a JavaScript click function that iterates through all records, not just the initial record

Although I'm new to web development and still learning the basics of html, javascript, etc., I have a problem that seems quite simple. The challenge lies in understanding javascript functions, which I find particularly tough to grasp. Here's what ...

You cannot assign a promise to a React state

Calling a function from MoviesPage.tsx to fetch movie data results in a promise containing an object that is successfully fetched (can confirm by console logging). However, I'm facing an issue when trying to assign the result to a state - receiving a ...

The form inputs within the modal are unresponsive to clicks

I recently began using bootstrap modals and had a separate register/login page from the index. I thought incorporating the login/register form into modals would be a good idea. However, inside the modal, all the inputs are not clickable - only accessible v ...

Discovering the Active Modal Form in BootStrap: Uncovering the Open Modal Form using JavaScript/jQuery

There are a total of 5 modal forms on my page. My goal is to identify the specific Id of the currently active one. One possible solution involves checking if $('#myModal').hasClass('in');. However, this method requires me to repeat the ...

Getting rid of quotes in a JSON result

My unique code snippet Retrieve data = Array[2] : 0:object id : "1" lat : "76.23" long:"21.92" 1:object id:"2" lat:"10.23" long:"12.92" var newCoords=[]; for(_i = 0; _i < ...

Issue with setting innerHTML of element in AngularJS app upon ng-click event

Look at this block of HTML: <div class="custom-select"> <div class="custom-select-placeholder"> <span id="placeholder-pages">Display all items</span> </div> <ul class="custom-select- ...

Angular does not assign the ng-invalid-class to the input

In order to register custom validation methods for custom form elements, we use extra directives as shown below: <ng-form name="validatorTestForm"> <our-input-directive name="validatorTest" ng-model="ourModel"/> ...

Conceal a card once verified within a bootstrap modal upon successful AJAX completion

On my delete page, there are multiple posts with a delete button. When the delete button is clicked, a Bootstrap modal opens asking for confirmation "Are you sure you want to delete this post? YES : NO" If the YES button is clicked, the .click(function(e) ...

I am experiencing an issue with the initial for-loop in my code as it is not

Upon clicking the start button, the score button, as well as the try again or correct button, are not being updated. Can someone help me figure out what's wrong? I believe the issue lies within this section of the code: for (i=0; i<5; i++) { do ...