Reputation: 355
I have created one field unique in my database. Consider the album name is unique. I have successfully added constraints that if user try to add other album with that name he will get error message that record already present. So user may not add any other record with the same name.
But now I have problem that if their are 3 records exists in database with name a,b,c.
and user is updating any of field than he can update record b
as name of a
so their would be two records in database with a
. & I want to create it unique. For that I am using script..
if($name!="") {
$sql = "select a_name from t_a_list where a_name = '$name'";
$result = mysql_query($sql);
if(mysql_num_rows($result) != 0) {
$msg = "<font color=red>Record Not Saved. Album already Exist!</font>";
}
} else {
$msg = "<font color=red>Enter Name of Album!</font>";
}
if($msg=="") {
//Update Query
}
But I have problem that with each pageload for updation I need to choose different name for album. because it will show album exist msg. Sometimes it might be possible that I want to change rest of information other than name of album like its year of release, total track. but with this script If I want to update rst of field I need to change album name first. Please help with this problem. So that album name may not repeat in DB and I can update other information also other than name.
Upvotes: 0
Views: 68
Reputation: 243
You could save the oldname in a variable and when updating first check for
.
this way you won't update the name unless it changed and the updates for the other fields will be made
if($name!=$oldname) { ...
$oldname = THE NAME OF THE ALBUM BEING EDITED
....
if($name!=$oldname) {
if($name!="") {
$sql = "select a_name from t_a_list where a_name = '$name'";
$result = mysql_query($sql);
if(mysql_num_rows($result) != 0) {
$msg = "Record Not Saved. Album already Exist!";
}
} else {
$msg = "Enter Name of Album!";
}
if($msg=="") {
//Update Query
}
}
if($description!="") {
....
}
if($location!="") {
...
}
...
Upvotes: 1
Reputation: 23779
You need to enforce the uniqueness constraint at the database level. This way, the database will reject any operation that will create records with identical keys.
One way to do this for an existing table is using the ALTER TABLE
command:
ALTER TABLE myalbums ADD UNIQUE (albumname);
Upvotes: 1