Saving Colors in the Database

6

I have a simple form, and a TYPE=color . These colors are passed in hexadecimal, but I can not save them in the database. Because it gives the following error:

  

Warning: pg_query (): Query failed: ERROR: input syntax is invalid for integer: "# 000000"

I've tried changing the bank, but it does not accept another entry. Does anyone have a solution?

    
asked by anonymous 18.11.2014 / 23:40

1 answer

7

The structure of your database provides for a relationship between two tables: the colors are stored in a table (if I understand correctly, the value of the color in hexadecimal), while the data of the clothes are in another. The clothes table makes a reference to the color table by recording the color code in a column that is a foreign key in> .

In this case, when inserting a new garment in the bank, what goes into the garment table is not the color value, but the color code as it appears in the other table (in column cd_cor ). To get the clothing data and its color in a single query, you use JOIN , as demonstrated in some other questions here on the site (for example, here and here ).

What I'm finding a little strange is that it does not make much sense to use a separate color table if your site allows you to choose any color instead of offering a limited number of options. If you had options like "navy blue" or "snow white", it makes sense to use the color chart. But if you want to write the color hex code, and accept any color in the 16+ million possible in this notation, it would be worth having a text-type column directly on the clothes table, and eliminate the relationship between the tables. >
  

Original response , written before the questioner post the database structure

I would recommend changing the data type in your table, and writing it as text. To do this in Postgres, you use ALTER TABLE . For example:

ALTER TABLE minhatabela
ALTER COLUMN nomedacoluna TYPE char(7);

However, if you really want to save the data as a number, PHP has the function hexdec which does the conversion with ease:

$preto = hexdec("#000000");    // 0
$branco = hexdec("#FFFFFF");   // 16777215
$azul = hexdec("#0000FF");     // 255
$verde = hexdec("#00FF00");    // 65280
$vermelho = hexdec("#FF0000"); // 16711680

You'll probably need to convert back to hexadecimal. You have dechex function for this, but you will need to put # and zeros to manually. For example, if you use only dechex :

$azul = dechex(255); // "FF" e não "#0000FF"

One way to resolve this:

"#" . substr("000000" . dechex(255), -6); // "#0000FF"
    
19.11.2014 / 01:21