Michael Cornn Michael Cornn - 1 year ago 150
MySQL Question

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

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

$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?

Answer Source

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


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download