在MySQL中存储RGB颜色。更好的char或int? [英] Store RGB colors in MySQL. Better as char or int?

查看:2921
本文介绍了在MySQL中存储RGB颜色。更好的char或int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用PHP从MySQL数据库查询CSS设置,然后将其回传到CSS样式表。示例代码段如下:

 <?php 
$ connect = //连接字符串
$ 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。';
}
';
?>

表displays对于设置的每个CSS属性都有一列。每行代表一组用户保存的颜色/字体/填充/边距设置。



font列是数据类型varchar(50)。什么数据类型应该是bgcolor? CSS希望看到一个十六进制值,但MySQL中没有十六进制数据类型。逻辑选择是将值存储为int类型,并在SELECT语句中使用HEX()函数。



再次,可能更容易和/或使用更少的空间只是存储它作为一个char(6)? PHP只是作为一个字符串,而不是一个实际的数字。十六进制值不会应用任何数学函数;



在这样的情况下,在将值存储为int或char之前是否有任何偏好?

解决方案

扩展我的评论:



由于这些值仅用于显示目的, CSS属性值完全,无论是什么,作为数据库中的字符串,例如:

 #ab382d 

这样就不需要在你的CSS中放置'#',所以你可以存储值




  • 透明

  • blue

  • rgb(100,100,100)

  • (或任何其他有效的背景颜色属性值)



编辑:您可能还想考虑一种缓存机制,以减少样式表信息对数据库的命中次数这可能不会太频繁变化。


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?

解决方案

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.

这篇关于在MySQL中存储RGB颜色。更好的char或int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆