ID's in phpmyadmin - php

I have a table in my phpmyadmin that contains some data for items that will be posted on a website. I'm adding these rows to the database manually. I want to show the number of the posted item. The first one will be '1', second one will be '2', etc. However if I use auto increment and delete the 2nd row there will be a gap in between. Suggestions to fix this?
I used PHP to display the ID of the row but when the second is deleted it shows the gap.
The structure starts with a column named 'id' which has a primary key and auto increment.

You don't want to do that! Period. You'll create yourself a lot of problems.
Your real issue is somewhere else. You think not having gaps between your ids will solve it. Solve that problem differently but leave the autoincremented id column alone. It is being implemented like that for a reason. The autoincrement makes sure you will never confuse two entries, it doesn't matter if there are gaps, you can always sort, you can always identify! If you need nice straight numbers, store your entries in a numeric array and use the keys for numbering. Or loop over your entries with a for loop and use the incrementor for numbering, or introduce an order column in your database.

Suggestions to fix this?
It's not broken!
You should not care or consider database ids as a developer, it is for internal use and data integrity.
If you really want to use incrementing numbers without gaps, use this in your query:
LIMIT 1 OFFSET X
Where X is the "id" in your url (not the real id).
However, listen to the folks here that are advising against this. It's not a very good idea and trust me, no one will care or even notice the forward facing database ids.

Related

Create Unique MYSQL Primary Key Where Only Part Of is Incremntal

In one of my mysql table, I need to generate the primary key field which is 15 digit in length.
Structure is 2+2+2+2+2+5 as ex: 010101010100001.
First 10 Digit values comes from five 2 digit form/input fields and last 5 character is unique and incremental. So, whenever a form/data is submitted that value will be increased.
now how can I achieve that?
I think of following method but thinking of 2 issue:
First use select query to get the last used id/number. Then add +1 to it.**
Issue-1:
For this I have to make 2 query 1 for select and 1 for update, but I think there is much better way than this?
Issue-2:
What if multiple like hundreds/thousands of users submit the form at the very same time? how can I make sure it will be unique and wont cause a db error?
any suggestion/idea would be highly appreciated.
Having a UNIQUE/PRIMARY KEY ensures that you cannot have any duplicate entries in the database. You will get an error message from MySQL if you try to create a duplicate entry. So you don't need to check for duplicates, MySQL will do so for you. However you have to check for error messages and react accordingly by changing the value like adding +1 on it, depending on your requirements.

How to force insert a duplicate key in mysql

It's a daily struggle to work with the previous programmer his code... And now, apparently, also his database.
Problem description
So here we've got a table to store the availability of a user and normally you would assign a unique id to every row of data. Except... he didn't. He made the user_id the first primary key (probably a composite).
So the user changes his availability for each weekday (monday to friday) and every timeslot in that week.
This is made into one row each:
user_id,day,hour_nr,hour_type,location_id
But you might see this one coming, I can't manually insert fake data for developing purposes. I'm trying to add a period and college year (it's for an educational institution) Which worked fine but because the old data didn't require this it's all set to 0.
The new row will consist of:
user_id,day,hour_nr,hour_type,location_id,period_id,collegeyear_id
I've tried uploading data to the table containing the period and college year information but I get an instant error telling me that there is a duplicate entry.
That's correct there is but there already were duplicates as well.
Question
And so the question is: how do I force this without altering the tables keys? I don't feel much for altering the indexed properties of the composite primary key.
Lastly, I know this is wrong and I know that it should have been done differently. Again it's not my work or design and I don't have any time on hand to fix or alter it during this project.
Edit
As requested, hereby a snapshot of the table with data and a snapshot of how it should be
The snapshot shows different headers than mentioned, they're the same but in Dutch.
Current data snapshot (I forgot to put the last 2 columns that are in the Desired data result snapshot on the snapshot but they're already there containing nothing but 0's)
Desired data result
I do need anINSERT, the data has to be added not altered. Or another fix for this issue ofcourse but the data has to be added.
Fix
So in a perfect example of tunnel vision I fixed and therefore answered my own question.
Instead of looking blindly at inserting the data I should have looked more towards the composite key part. I've added the 2 new columns to the key and now all is fine and dandy.
I said that I didn't want to mess with the keys but that was pointed towards the already existing keys not adding to the composite key.
I still dislike the fact that there isn't a single unique id but it is workable.
Q.
And so the question is: how do I force this without altering the tables keys? I don't feel much for altering the indexed properties of the composite primary key.
A.
You cannot force the primary key to have multiple values of the same ID.
The best thing for you to do would be to add an extra column with a new ID and reference that within the software.
A primary key is a special relational database table column (or combination of columns) designated to uniquely identify all table records.
A primary key’s main features are:
It must contain a unique value for each row of data.
It cannot contain null values.
A primary key is either an existing table column or a column that is specifically generated by the database according to a defined sequence.
Resources:- techopedia
So in a perfect example of tunnel vision I fixed and therefore answered my own question.
Instead of looking blindly at inserting the data I should have looked more towards the composite key part. I've added the 2 new columns to the key and now all is fine and dandy.
I said that I didn't want to mess with the keys but that was pointed towards the already existing keys not adding to the composite key.
I still dislike the fact that there isn't a single unique id but it is workable.

MySQL auto increment and select count

I am having a strange issue with MySQL Query, i am having a table with the fields
slno,mobileno , contractor with slno as primary key and auto
increment sequence 1
, while test say uptil 100 records the count and the autoincrement values are same ,
so i truncated the table to reset the autoincrement and inserted a huge excel file with around 40k data via php, then issued select query which yields
the max of slno is 40000 as expected but the count shows 39920
, I am just amused and tried to find over google , may be my lack of keyword search ability prevented me from finding result, so i am posting in here, for ref added screen shot, Any ideas and clarifications. Thanks
EDIT:
min slno is 1
EDIT :
A related question with solution to find gap in auto number in mysql has been asked and solved here.
There are specific cases in which auto-incremented values can be lost. One example is if you roll back an insertion. As per the doco:
"Lost" auto-increment values and sequence gaps
In all lock modes (0, 1, and 2), if a transaction that generated auto-increment values rolls back, those auto-increment values are "lost". Once a value is generated for an auto-increment column, it cannot be rolled back, whether or not the "INSERT-like" statement is completed, and whether or not the containing transaction is rolled back. Such lost values are not reused. Thus, there may be gaps in the values stored in an AUTO_INCREMENT column of a table.
In that case, although the insert is backed out, the auto-increment may not be. That would certainly allow for the possibility that your bulk insertion from Excel is occasionally failing and retrying, with the subsequent retry working. It really depends on how your insertion process works.
In any case, assuming those values will always be contiguous is actually a bad assumption to make.
This is because, even if insertions were guaranteed to be contiguous, it's possible to delete rows which would result in gaps appearing. You can certainly fix this each time you delete (or bulk insert for that matter) but the workload is high - you basically have to find gaps and then "move" higher entries into those gaps.
This movement is likely to be non-trivial as it's most likely that there will be other tables holding key look-ups to that column, and each of those will need to be changed as well.
So the best use case for an auto-increment field is simply to provide a unique identifier for the row where no other one exists and not to be necessarily contiguous.

Reserving a set of ids in autoincremented column

I have a table with autoincremented columnd 'id'.
The current AUTO_INCREMENT value is 99. So the next element, inserted to this table will have id=99.
I need to add a 1000 rows, forcing their ids to 2000-3000, and then reserve these values to not mess with others. I mean, after inserting these rows, I would like to return AUTO_INCREMENT value to 99, so that next row will have value 99, after that 100 and so on.
Regular ids will not raise higher than 1000, so I want them to get incremented in normal way.
I know it looks not so elegant, but it would make things a lot easier for a particular task.
Is is possible at all?
I need to add a 1000 rows, forcing their ids
Nope, You Don't
Autoincrement field is not what you think. It's unique identifier that's have no particular meaning at all. So - just leave it alone. If you want some sort of meaningful identifier - add another field and play with it whatever way you want.
Is is possible at all?
Fortunately - no.

Mysql phpMyAdmin few questions:

I am quite new to the mysql phpMyadmin environment, and I would like to have some area
1. I need a field of text that should be up to around 500 characters.
Does that have to be "TEXT" field? does it take the application to be responsible for the length ?
indexes. I understand that when I signify a field as "indexed", that means that field would have a pointer table and upon each a WHERE inclusive command, the search would be optimized by that field (log n complexity). But what happens if I signify a field as indexed after the fact ? say after it has some rows in it ? can I issue a command like "walk through all that table and index that field" ?
When I mark fields as indexed, I sometimes get them in phpMyAdmin as having the keyname
for accessing the table by the indexed field when I write php, does it take an extra effort on my side to use that keyname that is written down there at the "structure" view to use the table as indexed, or does that keyname is being used behind the scenes and I should not care about it whatsoever ?
I sometimes get the keynames referencing two or more fields altogether. The fields show one on top of the other. I don't know how it happened, but I need them to index only one field. What is going on ?
I use UTF-8 values in my db. When I created it, I think I marked it as utf8_unicode_ci, and some fields are marked as utf8_general_ci, does it matter ? Can I go back and change the whole DB definition to be utf8_general_ci ?
I think that was quite a bit,
I thank you in advance!
Ted
First, be aware that this not per se something about phpmyadmin, but more about mysql / databases.
1)
An index means that you make a list (most of the time a tree) of the values that are present. This way you can easily find the row with that/those values. This tree can be just as easily made after you insert values then before. Mind you, this means that all the "add to index" commands are put together, so not something you want to do on a "live" table with loads of entries. But you can add an index whenever you want it. Just add the index and the index will be made, either for an empty table or for a 'used' one.
2)
I don't know what you mean by this. Indexes have a name, it doesn't really matter what it is. A (primary) key is an index, but not all indexes are keys.
3)
You don't need to 'force' mysql to use a key, the optimizer knows best how and when to use keys. If your keys are correct they are used, if they are not correct they can't be used so you can't force it: in other words: don't think about it :)
4)
PHPMYADMIN makes a composite keys if you mark 2 fields as key at the same time. THis is annoying and can be wrong. If you search for 2 things at once, you can use the composite key, but if you search for the one thing, you can't. Just mark them as a key one at a time, or use the correct SQL command manually.
5)
you can change whatever you like, but I don't know what will happen with your values. Better check manually :)
If you need a field to contain 500 characters, you can do that with VARCHAR. Just set its length to 500.
You don't index field by field, you index a whole column. So it doesn't matter if the table has data in it. All the rows will be indexed.
Not a question
The indexes will be used whenever they can. You only need to worry about using the same columns that you have indexed in the WHERE section of your query. Read about it here
You can add as many columns as you wish in an index. For example, if you add columns "foo", "bar" and "ming" to an index, your database will be speed optimized for searches using those columns in the WHERE clause, in that order. Again, the link above explains it all.
I don't know. I'm 100% sure that if you use only UTF-8 values in the database, it won't matter. You can change this later though, as explained in this Stackoverflow question: How to convert an entire MySQL database characterset and collation to UTF-8?
I would recommend you scrap PHPMyAdmin for HeidiSQL though. HeidiSQL is a windows client that manages all your MySQL servers. It has lots of cool functions, like copying a table or database directly from one MySQL server to another. Try it out (it's free)

Categories