473,785 Members | 2,432 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Primary Keys

How is it that even though I have the column "username" in my database set
as a Primary key, using my PHP script to add new users to the database works
without any errors even when signing up using an existing username. I have a
database full of the same usernames!
Jul 16 '05 #1
6 3588
On Sun, 17 Aug 2003 15:43:00 +0000 (UTC), "John Simmons"
<Jo**********@h isPC.net> wrote:
How is it that even though I have the column "username" in my database set
as a Primary key, using my PHP script to add new users to the database works
without any errors even when signing up using an existing username. I have a
database full of the same usernames!


Which database? Can you post your table definition?

Without more information the only likely reasons are (a) you haven't actually
added the primary key correctly or (b) your database is severely broken.

--
Andy Hassall (an**@andyh.co. uk) icq(5747695) (http://www.andyh.co.uk)
Space: disk usage analysis tool (http://www.andyhsoftware.co.uk/space)
Jul 16 '05 #2

"John Simmons" <Jo**********@h isPC.net> wrote in message
news:bh******** **@hercules.bti nternet.com...
How is it that even though I have the column "username" in my database set
as a Primary key, using my PHP script to add new users to the database works without any errors even when signing up using an existing username. I have a database full of the same usernames!

PHP allows duplicate Primary Keys though it is not recommended at all. You
must specify that your primary key be "UNIQUE" when you add the primary key
field.

At your MySQL command prompt Try:

ALTER TABLE `thetable` ADD UNIQUE (`username`) ;

-JD
Jul 16 '05 #3
On Sun, 17 Aug 2003 16:00:46 GMT, "Jamie Davison" <ja***@bardavon .org> wrote:
"John Simmons" <Jo**********@h isPC.net> wrote in message
news:bh******* ***@hercules.bt internet.com...
How is it that even though I have the column "username" in my database set
as a Primary key, using my PHP script to add new users to the database
works without any errors even when signing up using an existing username. I have
a database full of the same usernames!

PHP allows duplicate Primary Keys though it is not recommended at all. You
must specify that your primary key be "UNIQUE" when you add the primary key
field.

At your MySQL command prompt Try:

ALTER TABLE `thetable` ADD UNIQUE (`username`) ;


Would you mind backing up this statement with some evidence please? PHP has
_nothing_ to do with primary keys, it's entirely the database's responsibility.
You can never have duplicate primary keys in a table; it's a contradiction.

A unique key constraint enforces uniqueness of a set of fields, which may
contain NULL values. You can have more than one unique key constraint on a
table.

A primary key constraint enforces uniqueness of a set of fields, which may NOT
contain NULL values. You can have only one primary key constraint on a table. A
primary key is also a unique identity of the entity represented by the row.

Since a primary key is more restrictive than a unique key, there's no point
adding a unique key on top of a primary key constraint (and you can't, anyway).

mysql> create table pktest (id int not null);
Query OK, 0 rows affected (0.04 sec)

mysql> alter table pktest add primary key (id);
Query OK, 0 rows affected (0.04 sec)
Records: 0 Duplicates: 0 Warnings: 0

mysql> alter table pktest add unique (id);
Query OK, 0 rows affected (0.02 sec)
Records: 0 Duplicates: 0 Warnings: 0

mysql> desc pktest;
+-------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| id | int(11) | | PRI | 0 | |
+-------+---------+------+-----+---------+-------+
1 row in set (0.01 sec)

The 'unique' specification gets ignored as it's redundant. Other databases may
reject it with an error (e.g. Oracle would say 'such column list already
indexed').

mysql> insert into pktest values (1);
Query OK, 1 row affected (0.00 sec)

mysql> insert into pktest values (1);
ERROR 1062: Duplicate entry '1' for key 1

Duplicates not allowed; it's a primary key.

--
Andy Hassall (an**@andyh.co. uk) icq(5747695) (http://www.andyh.co.uk)
Space: disk usage analysis tool (http://www.andyhsoftware.co.uk/space)
Jul 16 '05 #4
Andy Hassall wrote:

mysql> insert into pktest values (1);
Query OK, 1 row affected (0.00 sec)

mysql> insert into pktest values (1);
ERROR 1062: Duplicate entry '1' for key 1

Duplicates not allowed; it's a primary key.


I reckon he's not checking in his code to see if MySQL
raised an error; i.e., just executing the INSERT
and carrying on regardless...
Another case of "Please check mysql_error()". ..

Still working on the faq/wiki thing; just a bit worried
about potential bandwidth, although I may be able to get
it free on tuxfamily.org, given the nature of the site

Matt
Jul 16 '05 #5
On Sun, 17 Aug 2003 21:04:13 +0000 (UTC), "John Simmons"
<Jo**********@h isPC.net> wrote:
Ok, see attached zipped html file for details of my layout. And yes, we all
don't
like attachments in posts but it's far easier to read in this format than
trying to line up columns in a post. Please also bare in mind, I've only
been at this for a few weeks so I'm not asking for you to "Please check
mysql_error()" ..., I'm simply asking for some advice as I am sure you have
at times.

My PHP code to update the table goes as follows:

mysql_select_d b($DB);
$sql = "INSERT INTO " . $Table . " VALUES('','" . $_POST['username'] . "','"
. md5($_POST['password']) . "','" . $_POST['firstname'] . "','" .
$_POST['lastname'] . "','" . $_POST['email'] . "','" . $_POST['address1'] .
"','" . $_POST['address2'] . "','" . $_POST['county'] . "','" .
$_POST['postcode'] . "','" . $_POST['country'] . "')";
if(!($result = mysql_query($sq l)))
{
die(mysql_error ());
}

With this layout I would have expected to get some sort of error report back
about a duplicate key(?)


From the attached file:

Fields

Field Type Null Key Default Extra
ID
smallint(3)

PRI
(NULL)
auto_increment

username
varchar(15)

PRI
i.e. you have a composite primary key of (ID, username), meaning you're only
limiting unique usernames per value of ID. Since ID is auto_increment, you get
a new one each time.

What you want is primary key (ID), unique (username).

alter table member drop primary key;
alter table member add primary key (ID);
alter table member add unique (username);

You'll have to sort out the duplicates first, though.

--
Andy Hassall (an**@andyh.co. uk) icq(5747695) (http://www.andyh.co.uk)
Space: disk usage analysis tool (http://www.andyhsoftware.co.uk/space)
Jul 16 '05 #6
Excellent, just what I needed. Thanks for this Andy.

"Andy Hassall" <an**@andyh.co. uk> wrote in message
news:tq******** *************** *********@4ax.c om...
On Sun, 17 Aug 2003 21:04:13 +0000 (UTC), "John Simmons"
<Jo**********@h isPC.net> wrote:
Ok, see attached zipped html file for details of my layout. And yes, we alldon't
like attachments in posts but it's far easier to read in this format than
trying to line up columns in a post. Please also bare in mind, I've only
been at this for a few weeks so I'm not asking for you to "Please check
mysql_error()" ..., I'm simply asking for some advice as I am sure you haveat times.

My PHP code to update the table goes as follows:

mysql_select_d b($DB);
$sql = "INSERT INTO " . $Table . " VALUES('','" . $_POST['username'] . "','". md5($_POST['password']) . "','" . $_POST['firstname'] . "','" .
$_POST['lastname'] . "','" . $_POST['email'] . "','" . $_POST['address1'] .."','" . $_POST['address2'] . "','" . $_POST['county'] . "','" .
$_POST['postcode'] . "','" . $_POST['country'] . "')";
if(!($result = mysql_query($sq l)))
{
die(mysql_error ());
}

With this layout I would have expected to get some sort of error report backabout a duplicate key(?)
From the attached file:

Fields

Field Type Null Key Default Extra
ID
smallint(3)

PRI
(NULL)
auto_increment

username
varchar(15)

PRI
i.e. you have a composite primary key of (ID, username), meaning you're

only limiting unique usernames per value of ID. Since ID is auto_increment, you get a new one each time.

What you want is primary key (ID), unique (username).

alter table member drop primary key;
alter table member add primary key (ID);
alter table member add unique (username);

You'll have to sort out the duplicates first, though.

--
Andy Hassall (an**@andyh.co. uk) icq(5747695) (http://www.andyh.co.uk)
Space: disk usage analysis tool (http://www.andyhsoftware.co.uk/space)

Jul 16 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

17
49833
by: Philip Yale | last post by:
I'm probably going to get shot down with thousands of reasons for this, but I've never really heard or read a convincing explanation, so here goes ... Clustered indexes are more efficient at returning large numbers of records than non-clustered indexes. Agreed? (Assuming the NC index doesn't cover the query, of course) Since it's only possible to have one clustered index, why is this almost always used for the primary key, when by...
7
2958
by: Ilan Sebba | last post by:
I am trying to add a record using SQL. My problem is that the primary keys are foreign keys, and these foreign keys are autonumbers. I therefore do not know the primary keys of the record I am trying to insert. I therefore do not think that I can use the sql "Insert Into" command. Here is a simplified illustration of my tables: tblFather NaturalKey1 NatuarlKey2
5
4552
by: Geoff Cayzer | last post by:
At http://www.blueclaw-db.com/tips_tricks.htm I came across a section which is included below and was hoping for some comment on the article. -------------- Almost never use this auto-number field as the primary key of the table. If you are thinking of hiring an Access programmer or consultant ask
7
5353
by: Philip | last post by:
Hey all, (Access 2000) I've been having a horror story with this design problem. My Database is Structured like This: AUTHORS, BOOKS, PAGES. Those are the Tables and each Item in each table needs a unique ID# based on its context. Primary Keys AUTHORS = AuthorID - NO Duplicates
18
12667
by: Thomas A. Anderson | last post by:
I am a bit confused in creating a composite primary key. I have three table with two of the tables containing primary keys. I have two of the tables (each with a primary key) having one to many relations with the table containing no primary key. Do I just create two primary keys on the table that does not contain any primary key for this to become a composite primary key? Thank you in advance! Still a newbie,
7
2468
by: Dave | last post by:
Hi, Maybe I'm missing something with the DataKeyField attribute of a datagrid but it seems that it's somewhat limiting since this only allows you to specify one field as the key. I have a table that has two keys and it seems you need this value to find the corresponding record in the DataSet in order to update the data from the Datagrid.
1
1856
by: GGerard | last post by:
Hello I'm trying to find the best way to set indexes and primary keys on MSAccess tables What are the advantages and disadvantages of indexes and primary keys? What fields should be indexed? Should I index more than one field per table? What fields should have the primary key?
9
3911
by: sonal | last post by:
Hi all, I hv started with python just recently... and have been assigned to make an utility which would be used for data validations... In short we take up various comma separated data files for eg: area.txt, school.txt, students.txt.... and so on (ok?!?) now, 1. area code used in the school.txt must be defined in the area.txt (Primary key in area => area_code defined in area.txt & Foreign key on school => area_code defined in...
115
6274
by: LurfysMa | last post by:
Most of the reference books recommend autonum primary keys, but the Access help says that any unique keys will work. What are the tradeoffs? I have several tables that have unique fields. Can I use them as primary keys or should I define an autonum primary key? One table has information about the 50 states in the US. The table looks like this:
2
9166
by: Danny | last post by:
Hello, We imported a bunch of tables from a database and realized that the primary keys weren't copied to the destination db. In order to re- create the keys, we need to know which tables have them. Is there a command that I can use (on the source db) to find out which tables contain primary keys? The db has hundreds of tables and I'd rather not go through each one to see which has a primary key. Also, for future reference, is there a...
0
9645
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9480
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10325
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10147
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10091
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9950
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8972
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5381
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.