Database numeric field starting with 0 - php

I am using a field named as area_code that has int data-type in MySQL. But it doesn't allow me to store exact values like 0781, 0727, 0788 Bcoz they are starting with 0.
It stores the values as 781, 727 and 788 i.e. it truncates 0 from the values and save it.
Please help me..

Area codes are not numbers, but text (which contains digits only). Declare area_code as a varchar field of appropriate size.

drop table if exists foo;
create table foo
(
area_code smallint(4) unsigned zerofill not null default 0
)
engine=innodb;
insert into foo (area_code) values (781),(727);
select * from foo;
+-----------+
| area_code |
+-----------+
| 0781 |
| 0727 |
+-----------+
http://dev.mysql.com/doc/refman/5.0/en/numeric-types.html

Use a character based data-type rather than a numeric data-type.

Use VARCHAR, because you don't need to make any arithmetic actions with area codes

if you want your result as 4 digits you can maybe do it in this way:
select lpad(area_code, 4, '0') from zipcode_list;
now you can store the 3 numbers in your database and returning the zero before.

Related

Auto Increment From A Six Seven Number

I know this may seem like a similar question out there, but it really is not. I am trying to create a seven digit ID number that is saved in my mySQL database.
I'm using this sprintf("%07d", $idNumber);
This works, and creates a seven digit id number. However, I want to insert this into my database. The problem is I don't know how to increment this ID number then insert it into the database.
Any ideas?
Thanks!
You can define a column with the ZEROFILL option, and then insert unformatted integers.
mysql> create table foo (id int(7) zerofill auto_increment primary key);
mysql> insert into foo values (123);
mysql> insert into foo () values ();
mysql> select * from foo;
+---------+
| id |
+---------+
| 0000123 |
| 0000124 |
+---------+
This is the only time the numeric argument to the INT type has any practical use. I wish they had made the argument on the ZEROFILL keyword instead of the INT keyword. It would have avoided a lot of confusion.

Maintain 4 digits in database INT? [duplicate]

I just want to know what is the benefit/usage of defining ZEROFILL for INT DataType in MySQL?
`id` INT UNSIGNED ZEROFILL NOT NULL
When you select a column with type ZEROFILL it pads the displayed value of the field with zeros up to the display width specified in the column definition. Values longer than the display width are not truncated. Note that usage of ZEROFILL also implies UNSIGNED.
Using ZEROFILL and a display width has no effect on how the data is stored. It affects only how it is displayed.
Here is some example SQL that demonstrates the use of ZEROFILL:
CREATE TABLE yourtable (x INT(8) ZEROFILL NOT NULL, y INT(8) NOT NULL);
INSERT INTO yourtable (x,y) VALUES
(1, 1),
(12, 12),
(123, 123),
(123456789, 123456789);
SELECT x, y FROM yourtable;
Result:
x y
00000001 1
00000012 12
00000123 123
123456789 123456789
One example in order to understand, where the usage of ZEROFILL might be interesting:
In Germany, we have 5 digit zipcodes. However, those Codes may start with a Zero, so 80337 is a valid zipcode for munic, 01067 is a zipcode of Berlin.
As you see, any German citizen expects the zipcodes to be displayed as a 5 digit code, so 1067 looks strange.
In order to store those data, you could use a VARCHAR(5) or INT(5) ZEROFILL whereas the zerofilled integer has two big advantages:
Lot lesser storage space on hard disk
If you insert 1067, you still get 01067 back
Maybe this example helps understanding the use of ZEROFILL.
It's a feature for disturbed personalities who like square boxes.
You insert
1
23
123
but when you select, it pads the values
000001
000023
000123
It helps in correct sorting in the case that you will need to concatenate this "integer" with something else (another number or text) which will require to be sorted as a "text" then.
for example,
if you will need to use the integer field numbers (let's say 5) concatenated as A-005 or 10/0005
I know I'm late to the party but I find the zerofill is helpful for boolean representations of TINYINT(1). Null doesn't always mean False, sometimes you don't want it to. By zerofilling a tinyint, you're effectively converting those values to INT and removing any confusion ur application may have upon interaction. Your application can then treat those values in a manner similar to the primitive datatype True = Not(0)
mysql> CREATE TABLE tin3(id int PRIMARY KEY,val TINYINT(10) ZEROFILL);
Query OK, 0 rows affected (0.04 sec)
mysql> INSERT INTO tin3 VALUES(1,12),(2,7),(4,101);
Query OK, 3 rows affected (0.02 sec)
Records: 3 Duplicates: 0 Warnings: 0
mysql> SELECT * FROM tin3;
+----+------------+
| id | val |
+----+------------+
| 1 | 0000000012 |
| 2 | 0000000007 |
| 4 | 0000000101 |
+----+------------+
3 rows in set (0.00 sec)
mysql>
mysql> SELECT LENGTH(val) FROM tin3 WHERE id=2;
+-------------+
| LENGTH(val) |
+-------------+
| 10 |
+-------------+
1 row in set (0.01 sec)
mysql> SELECT val+1 FROM tin3 WHERE id=2;
+-------+
| val+1 |
+-------+
| 8 |
+-------+
1 row in set (0.00 sec)
ZEROFILL
This essentially means that if the integer value 23 is inserted into an INT column with the width of 8 then the rest of the available position will be automatically padded with zeros.
Hence
23
becomes:
00000023
When used in conjunction with the
optional (nonstandard) attribute
ZEROFILL, the default padding of
spaces is replaced with zeros. For
example, for a column declared as
INT(4) ZEROFILL, a value of 5 is
retrieved as 0005.
http://dev.mysql.com/doc/refman/5.0/en/numeric-types.html
If you specify ZEROFILL for a numeric column, MySQL automatically adds the UNSIGNED attribute to the column.
Numeric data types that permit the UNSIGNED attribute also permit SIGNED. However, these data types are signed by default, so the SIGNED attribute has no effect.
Above description is taken from MYSQL official website.

Is there any need to ensure correct data type is submitted to MySQL database?

After writing a PHP function to ensure data parsed from a csv is inputed as its correct format (to match the column data type set when creating the table), I've learned that MySQL by default will output all values as strings anyway.
My question is therefore - is there any need to ensure an integer (for an id column that has been set to store integers only) IS an integer and not a string containing a number ( "1" for example) before inserting into MySQL database?
If not, then what is the thinking behind explicitly stating what values a column should store when creating tables in MySQL?
The values are being converted between string and integer. When inserting a row into MySQL both PHP and MySQL can convert a string of "1" into an integer 1. Try passing a string "notanumber" into an Integer field, it's not going to work because you can't convert that string value into a number. The reason MySQL returns strings in selecting is so everything is in one type of format, there may be another reason for it - but it's easier to know everything in your results is a string and not have to check if it's an integer, or a float, or whatever else. With PHP and implicit conversion this isn't a huge deal, but for a language like C# that is very strongly typed this can save a lot of time. You know it's a string, and convert to what you want if need be instead of checking for tons of different possibilities.
You definitely should be checking data before inserting, or at least handling the MySQL errors if you don't. You can check using isset($var) for null or empty values, is_numeric($var) for integers, is_float($var) for floats. I would recommend validating everything before putting it into the database.
A lot of data types will be automaticly cast towards the correct type in MySQL. I.e. inserting a number to a varchar field will become a string.
The thinking about stating the column types have several reason, mostly for speed and space optimization. Off course you can create all fields as varchars, but storing the number 300000000 in a varchar field would need (at least) 9 bytes while for an integer field a basic 32bit (4 bytes) would be enough. Comparing integer numbers (in the where clause) is easy, but numbers in strings is different. I.e. ordering string cat,cars,car will be: car, cars, cat. But how would you order strings 1000,1200 and 10000? As strings it would be 1000, 10000, 1200. As numbers 1000,1200 and 10000.
For ints/strings, data types aren't too critical while inserting. You can probably find some edge cases where an exotic floating point value-as-string doesn't insert properly. MySQL for the most part will do the right thing when forced to do type juggling while inserting. A string inserted into a numeric-type field will get converted to a number, as best as MySQL can.
The major problem is when it comes time to actually USE the data you've inserted. That's when number v.s. string distinctions become critical:
mysql> create table test (strings varchar(2), integers int);
Query OK, 0 rows affected (0.00 sec)
mysql> insert into test values ('12', 12), ('2', 2), ('112', 112);
Query OK, 3 rows affected (0.00 sec)
Records: 3 Duplicates: 0 Warnings: 0
mysql> select * from test;
+---------+----------+
| strings | integers |
+---------+----------+
| 12 | 12 |
| 2 | 2 |
| 112 | 112 |
+---------+----------+
3 rows in set (0.00 sec)
Simple select, sorting via the integer field:
mysql> select * from test order by integers;
+---------+----------+
| strings | integers |
+---------+----------+
| 2 | 2 |
| 12 | 12 |
| 112 | 112 |
+---------+----------+
Everything ok with integer sorting. We get nicely sorted ascending list.
But when it comes time for the strings:
mysql> select * from test order by strings asc;
+---------+----------+
| strings | integers |
+---------+----------+
| 112 | 112 |
| 12 | 12 |
| 2 | 2 |
+---------+----------+
Ooops... totally wrong. MySQL (properly) sorted as strings, and by string rules, 112 is smaller than 2.

Searching MySQL data

I am trying to search MySQL database with a search key entered by the user. My data contain upper case and lower case. My question is how to make my search function not case sensitive. ex:data in mysql is BOOK but if the user enters book in search input. The result is not found....Thanks..
My search code
$searchKey=$_POST['searchKey'];
$searchKey=mysql_real_escape_string($searchKey);
$result=mysql_query("SELECT *
FROM product
WHERE product_name like '%$searchKey%' ORDER BY product_id
",$connection);
Just uppercase the search string and compare it to the uppercase field.
$searchKey= strtoupper($_POST['searchKey']);
$searchKey=mysql_real_escape_string($searchKey);
$result=mysql_query("SELECT * FROM product
WHERE UPPER(product_name) like '%$searchKey%' ORDER BY product_id
",$connection);
If possible, you should avoid using UPPER as a solution to this problem, as it incurs both the overhead of converting the value in each row to upper case, and the overhead of MySQL being unable to use any index that might be on that column.
If your data does not need to be stored in case-sensitive columns, then you should select the appropriate collation for the table or column. See my answer to how i can ignore the difference upper and lower case in search with mysql for an example of how collation affects case sensitivity.
The following shows the EXPLAIN SELECT results from two queries. One uses UPPER, one doesn't:
DROP TABLE IF EXISTS `table_a`;
CREATE TABLE `table_a` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`value` varchar(255) DEFAULT NULL,
INDEX `value` (`value`),
PRIMARY KEY (`id`)
) ENGINE=InnoDB;
INSERT INTO table_a (value) VALUES
('AAA'), ('BBB'), ('CCC'), ('DDD'),
('aaa'), ('bbb'), ('ccc'), ('ddd');
EXPLAIN SELECT id, value FROM table_a WHERE UPPER(value) = 'AAA';
+----+-------------+---------+-------+---------------+-------+---------+------+------+--------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+---------+-------+---------------+-------+---------+------+------+--------------------------+
| 1 | SIMPLE | table_a | index | NULL | value | 258 | NULL | 8 | Using where; Using index |
+----+-------------+---------+-------+---------------+-------+---------+------+------+--------------------------+
EXPLAIN SELECT id, value FROM table_a WHERE value = 'AAA';
+----+-------------+---------+------+---------------+-------+---------+-------+------+--------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+---------+------+---------------+-------+---------+-------+------+--------------------------+
| 1 | SIMPLE | table_a | ref | value | value | 258 | const | 2 | Using where; Using index |
+----+-------------+---------+------+---------------+-------+---------+-------+------+--------------------------+
Notice that the first SELECT which uses UPPER has to scan all the rows, whereas the second only needs to scan two - the two that match. On a table this size, the difference is obviously imperceptible, but with a large table, a full table scan can seriously impact the speed of your query.
This is an easy way to do it:
$searchKey=strtoupper($searchKey);
SELECT *
FROM product
WHERE UPPER(product_name) like '%$searchKey%' ORDER BY product_id
First of all, try to avoid using * as much as possible. It is generally considered a bad idea. Select the columns using column names.
Now, your solution would be -
$searchKey=strtoupper($_POST['searchKey']);
$searchKey=mysql_real_escape_string($searchKey);
$result=mysql_query("SELECT product_name,
// your other columns
FROM product
WHERE UPPER(product_name) like '%$searchKey%' ORDER BY product_id
",$connection);
EDIT
I will try to explain why it is a bad idea to use *. Suppose you need to change the schema of the product table(adding/deleting columns). Then, the columns that are being selected through this query will change, which may cause unintended side effects and will be hard to detect.
According to the MySQL manual, case-sensitivity in searches depends on the collation used, and should be case-insensitive by default for non binary fields.
Make sure you have the field types and the query right (maybe there's an extra space or something). If that doesn't work, you can convert the string to upper case in PHP (ie: $str = strtoupper($str)) and do the same on the MySQL side (#despart)
EDIT: I posted the article above (^). AndI just tested it. Searches on CHAR, VARCHAR, and TEXT fields are case-insensitive (collation = latin1)

Can't insert new row into postgres database table?

I have an issue, I'm trying to insert a new row into a postgres database table and get the following error
ERROR: duplicate key violates unique constraint "n_clients_pkey"
Here my query
insert into n_clients(client_name) values( 'value');
I'm using postgres 8.1.11
PostgreSQL 8.1.11 on x86_64-redhat-linux-gnu, compiled by GCC gcc (GCC) 4.1.2 20070626 (Red Hat 4.1.2-14)
Here's the structure for my table
Table "public.n_clients"
Column | Type | Modifiers
-------------+--------------------------+-----------------------------------------------------------------------
id | integer | not null default nextval(('public.n_clients_id_seq'::text)::regclass)
client_name | character varying(200) | not null
moddate | timestamp with time zone | default now()
createdate | timestamp with time zone | default now()
Indexes:
"n_clients_pkey" PRIMARY KEY, btree (id)
and the sequence
Sequence "public.n_clients_id_seq"
Column | Type
---------------+---------
sequence_name | name
last_value | bigint
increment_by | bigint
max_value | bigint
min_value | bigint
cache_value | bigint
log_cnt | bigint
is_cycled | boolean
is_called | boolean
This row exists already, therefore you cannot insert it. What is the primary key of your relation? Is it a sequence? If so, maybe it got stuck (maybe you imported data). You should reset it manually to the next free ID available (e.g., if the maximum ID is 41, you should do: SELECT setval('your_seq', 42);) then try again.
You must have a UNIQUE constraint on your table, that your insert is violating -- ie, considering the name of your table and index, you are probably trying to insert a client that already exists in your table.
Typically one gets into this situation by manually adding a record with an id field that matches the current value for the sequence. It's easy to introduce this by some common dump/reload operations for example. I wrote an article about correcting for this sort of error across the entire database at Fixing Sequences.
The PostGresSQL should have a primary key while creating a DB , so you are not able to add anything include then only you can add data manually
8.1 version is dated.
8.4 displays a much better error message :
ERROR: duplicate key value violates unique constraint "master_pkey"
DETAIL: Key (id)=(1) already exists.

Categories