Primary key issue in MySql using PhPMyadmin - php

I recently started learning some languages: html, css and now PhP and MySql. I created a sign up, log in and log out system using this tutorial:
http://www.tutorialrepublic.com/php-tutorial/php-mysql-login-system.php
I'm using XAMPP to run Apache server, MySql and PhPMyAdmin. Everything seems to work fine, except for an issue with the primary key. When my form was completed I started adding some fictional user accounts to test it out. After that I deleted them. The username and password were deleted, but the Primary Key (ID) won't change. Even though the first row should be the first ID of 1, it is stuck at 3 because the rows with ID's 1 and 2 were deleted. With this as a result:
image of issue.
Can anyone help me with this?

That's the AUTO_INCREMENT behavior. As you can see here, you can modify your auto_increment setting something like this:
ALTER TABLE foo AUTO_INCREMENT=1
But this isn't recommended.

In the table creation the id is set to auto_increment
CREATE TABLE users (
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(50) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
This causes the numbers to keep incrementing even though they may not be in the database.
You can reset the auto_increment value:
ALTER TABLE `table_name` AUTO_INCREMENT=1

You can either truncate your table (Operations tab in PHPMyAdmin) or run the following query:
ALTER TABLE `mytable` AUTO_INCREMENT = 1;
But just truncate it, it's best to just do that.

Related

How do i make laravel auto incement work on clear db [duplicate]

I have a simple table in ClearDB:
CREATE TABLE `users` (
`id` smallint(6) unsigned NOT NULL AUTO_INCREMENT,
`username` varchar(100) DEFAULT NULL,
`message` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=INNODB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;
I'm using Node to insert data into the table via:
var post = {username: response.user.name, message: message.text};
connection.query("INSERT INTO users SET ?", post, function(err, rows, fields) {
if (err) {
console.log('error: ', err);
throw err;
}
});
However whenever I insert my id field increases by 10 rather than 1 (and it started off with 12:
id username message
12 test test
22 test test
32 test test
42 test test
Any idea why this is happening?
Thanks!
It is ClearDB's strategy. Here is the explanation from ClearDB's website.
You can't change this auto_increment step when you are using ClearDB.
This is the explanation from the link above.
ClearDB uses circular replication to provide master-master MySQL
support. As such, certain things such as auto_increment keys (or
sequences) must be configured in order for one master not to use the
same key as the other, in all cases. We do this by configuring MySQL
to skip certain keys, and by enforcing MySQL to use a specific offset
for each key used. The reason why we use a value of 10 instead of 2 is
for future development.
I had the same problem. After some digging I found that I can change the auto_increment
Check first what value it is
SELECT ##auto_increment_increment
Then change it
SET ##auto_increment_increment=1;
This seems to be because of AUTO_INCREMENT field
remove AUTO_INCREMENT=11

PhpMyAdmin SQL code not showing up when creating new database and table

I'm using WampServer with phpmyadmin, but have also tried Xamp and same results.
I have 6 entries in the table called employees:
I have a table called employee with entries:
empId, lastName, firstName, department, position, and salary.
empId is primary key w/ auto increment. I'm following a tutorial online where they are using a mac computer, I'm on windows, in case that has something to do with the issue.
When I look at the SQL this produces it shows this:
SELECT * FROM `employee` WHERE 1
I don't see any CreateTable or other SQL.
Can anyone shed some light as to what is going on here?
Thank you.
UPDATE:
So if I go to > Export to SQL:
And this is what I get:
CREATE TABLE IF NOT EXISTS employee (
empId int(11) NOT NULL,
lastName varchar(40) NOT NULL,
firstName varchar(20) NOT NULL,
department int(2) NOT NULL,
position varchar(20) NOT NULL,
salary int(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE employee
ADD PRIMARY KEY (empI);
Which looks like the correct SQL.
So at least I know it is creating the correct SQL even though its not showing on the phpmyadmin web gui page.
A CREATE TABLE statement is just a command to create a table. You can also create a table using the GUI of PHPMyAdmin, in which case it performs the necessary actions for you.
But those are just commands, blue-prints if you like. In the database itself the 'Create table' statement doesn't exist. The database contains an actual table which was created using such a statement. When you export the database (like you did) or ask for the create table statement, it just reverse-engineers the actual table structure into a statement, like drawing a blue-print based on an actual object you have.
PHPMyAdmin will often show the statement that it generated to build -for instance- a table, but in some cases you may not see it. It might be that the guy of the tutorial has a slightly different version of PHPMyAdmin, or he activated a feature that shows the statement.

foreign keys mysql and phpmyadmin

I'm developing a website with php + mysql(phpMyAdmin).
I got 2 tables: USERS and FOLLOWERS like in the link i've pasted here below:
These tables are created with a sql script that I paste here bellow:
DROP TABLE IF EXISTS `FOLLOWERS`;
CREATE TABLE IF NOT EXISTS `FOLLOWERS` (
`Follower1_Id` int(10) unsigned NOT NULL,
`Follower2_Id` int(10) unsigned NOT NULL,
PRIMARY KEY (`Follower1_Id`, `Follower2_Id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;
(I just paste the table "FOLLOWERS" due to in that table is where is the problem).
Due to i don't know why phpMyAdmin doesn't allow to insert foreign keys, the problem comes when i try to insert a follower based on the USERS table. For any reason i can insert the user nÂș5 when i only have 3 users and these users have 1,2,3 as a User_Id PK.
Apparently I used the relational mode that phpMyAdmin offers me but there's no result.
What can i do?
The table you created is an MyISAM table and unfortunately they don't support Foreign Keys.
http://www.sitepoint.com/mysql-myisam-table-pros-con/
In PHPMyAdmin you can easily convert it from an MyISAM to an InnoDB table. This should enable the foreign Key features you're after.
When you say :
phpMyAdmin doesn't allow to insert foreign keys, the problem comes
when i try to insert a follower based on the USERS table.
What type of error do you get?
Could you give us more information?
MyISAM table doesn't support Foreignkey and it only supports Primary key. But you can convert it into InnoDB table and then you can assign Foreign key to it.

Composite keys with AUTO_INCREMENT and CURRENT_TIMESTAMP working together

Similarly to many other questions about composite keys with AUTO_INCREMENT, I am receiving the following error:
Incorrect table definition; there can be only one auto column and it must be defined as a key
What I'm doing is making a history trail of all changes in the table. Every time a change is made, a new row is inserted with a new timestamp, leaving previous modifications untouched.
My DDL in concern is this:
DROP TABLE IF EXISTS personnel;
CREATE TABLE IF NOT EXISTS personnel
(
modified TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
id INTEGER UNSIGNED AUTO_INCREMENT NOT NULL,
...
PRIMARY KEY (modified, id),
...
) ENGINE=InnoDB;
I presume that I'm getting this error because I am using both CURRENT_TIMESTAMP and AUTO_INCREMENT. So is there a way to resolve this without making PHP do the timestamp generation (so my model can just insert as if it were any other table, letting the controller do the dirty work).
MySQL's error message has more to be desired...
The autoincrementing column has to be at the beginning of an index. In your case you need to add another index - KEY id(id).

MYSQL QUERY to retrieve the data

I have the following schema with the following attributes:
USER(TABLE_NAME)
USER_ID|USERNAME|PASSWORD|TOPIC_NAME|FLAG1|FLAG2
I have 2 questions basically:
How can I make an attribute USER_ID as primary key and it should
automatically increment the value each time I insert the value into
the database.It shouldn't be under my control.
How can I retrieve a record from the database, based on the latest
time from which it was updated.( for example if I updated a record
at 2pm and same record at 3pm, if I retrieve now at 4pm I should get
the record that was updated at 3pm i.e. the latest updated one.)
Please help.
I'm assuming that question one is in the context of MYSQL. So, you can use the ALTER TABLE statement to mark a field as PRIMARY KEY, and to mark it AUTOINCREMENT
ALTER TABLE User
ADD PRIMARY KEY (USER_ID);
ALTER TABLE User
MODIFY COLUMN USER_ID INT(4) AUTO_INCREMENT; -- of course, set the type appropriately
For the second question I'm not sure I understand correctly so I'm just going to go ahead and give you some basic information before giving an answer that may confuse you.
When you update the same record multiple times, only the most recent update is persisted. Basically, once you update a record, it's previous values are not kept. So, if you update a record at 2pm, and then update the same record at 3pm - when you query for the record you will automatically receive the most recent values.
Now, if by updating you mean you would insert new values for the same USER_ID multiple times and want to retrieve the most recent, then you would need to use a field in the table to store a timestamp of when each record is created/updated. Then you can query for the most recent value based on the timestamp.
I assume you're talking about Oracle since you tagged it as Oracle. You also tagged the question as MySQL where the approach will be different.
You can make the USER_ID column a primary key
ALTER TABLE <<table_name>>
ADD CONSTRAINT pk_user_id PRIMARY KEY( user_id );
If you want the value to increment automatically, you'd need to create a sequence
CREATE SEQUENCE user_id_seq
START WITH 1
INCREMENT BY 1
CACHE 20;
and then create a trigger on the table that uses the sequence
CREATE OR REPLACE TRIGGER trg_assign_user_id
BEFORE INSERT ON <<table name>>
FOR EACH ROW
BEGIN
:new.user_id := user_id_seq.nextval;
END;
As for your second question, I'm not sure that I understand. If you update a row and then commit that change, all subsequent queries are going to read the updated data (barring exceptionally unlikely cases where you've set a serializable transaction isolation level and you've got transactions that run for multiple hours and you're running the query in that transaction). You don't need to do anything to see the current data.
(Answer based on MySQL; conceptually similar answer if using Oracle, but the SQL will probably be different.)
If USER_ID was not defined as a primary key or automatically incrementing at the time of table creation, then you can use:
ALTER TABLE tablename MODIFY USER_ID INT NOT NULL PRIMARY KEY AUTO_INCREMENT;
To issue queries based on record dates, you have to have a field defined to hold date-related datetypes. The date and time of record modifications would be something you would manage (e.g. add/change) based on the way in which you are accessing the records (some PHP-related way? it's unclear what scripts you have in play, based on your question.) Once you have dates in your records you can ORDER BY the date field in your SELECT query.
Check this out
For your AUTOINCREMENT, Its a question already asked here
For your PRIMARY KEY use this
ALTER TABLE USER ADD PRIMARY KEY (USER_ID)
Can you provide more information. If the value gets updated you definitely do NOT have your old value that you entered at 2pm present in the dB. So querying for it will be fine
You can use something like this:
CREATE TABLE IF NOT EXISTS user (
USER_ID unsigned int(8) NOT NULL AUTO_INCREMENT,
username varchar(25) NOT NULL,
password varchar(25) NOT NULL,
topic_name varchar(100) NOT NULL,
flag1 smallint(1) NOT NULL DEFAULT 0,
flag2 smallint(1) NOT NULL DEFAULT 0,
update_time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (uid)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
For selection use query:
SELECT * from user ORDER BY update_time DESC

Categories