Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store RGB colors in MySQL. Better as char or int?

Tags:

css

php

mysql

rgb

I'm using PHP to query CSS settings from a MySQL database, which is then echoed into a CSS stylesheet. Sample snippet is below:

<?php
    $connect = //connect string
    $query = ($connect, "SELECT bgcolor, font FROM displays WHERE name = 'mySettings'");
    while ($row = mysqli_query($query)){
        $bgcolor = $row[bgcolor];
        $font = $row[font];
    }
    echo '
        body {
            background-color: #'.$bgcolor.';
            font: '.$font.';
        }
    ';
?>

The table "displays" has one column for each CSS property that's set. Each row represents a set of color/font/padding/margin settings the user has saved.

The column "font" is data type varchar(50). What data type should "bgcolor" be? CSS wants to see a hex value, but there's no hex datatype in MySQL. The logical choice would be to store the value as type int and use the HEX() function in the SELECT statement.

Then again, might it be easier and/or use less space to just store it as a char(6)? PHP is just treating as a string, not an actual number. The hex value won't have any mathematical functions applied to it; it's just pasted into the CSS.

In a case like this, is there any preference between storing the value as an int or a char?

like image 242
Bagheera Avatar asked Dec 02 '22 19:12

Bagheera


1 Answers

Expanding on my comment:

Since the values are for display purposes only, I would store the CSS attribute value entirely, whatever it may be, as a string in the database, e.g.:

#ab382d

This would eliminate the need to have the '#' sitting there in your CSS, so you could then potentially store values such as

  • transparent
  • blue
  • rgb(100, 100, 100)
  • (or any other valid background-color attribute value)

without needing to know how to render it.

EDIT: You may also want to think about a caching mechanism to reduce the number of hits to the database for stylesheet information that probably doesn't change too often.

like image 114
Cᴏʀʏ Avatar answered Dec 05 '22 10:12

Cᴏʀʏ