I have a table with 5 rows. Every time a user enters data into a form, it is entered into the table. My first column is called id and holds the number of the post. What I want to do is get the value of id from the previous row, add one to it and set it as the value in the current post's id field. How do I do this?
Just set that field as primary key and auto-increment, it will automatically do this for you. You won't have to fetch the previous row and add that field value to next one.
The SQL query you need is:
SELECT max(id)
FROM tableName;
Set attribute auto increment for "ID" field in the table that contains 5 columns.
You can use sql query like
"INSERT INTO my_table (id auto_increment,primary key(id))";
then you can get...
and eachtime you need not worry to insert id ,it will automatically increments
I would not recomend doing this as it could lead to a race condition.
Change the table structure and set the id field to be the primary key and set it to auto increment. This way anytime a new row is added, it will auto-magically be assigned the next ID.
see this answer on details of how to set auto increment.
here is the query to alter your table and it will set your field or column as primary key and also auto increment it.
ALTER TABLE tbl ADD id INT PRIMARY KEY AUTO_INCREMENT;
Related
I have a php script that logs inputs from a form into a mysql database table. I'm looking for a way to insert this data untill 3 rows are created, after which it has to update the existing rows so that the first one updates to the new input, the second one to the former first input and the third one to the former second input.
Table:
CREATE TABLE IF NOT EXISTS inputlog (
id int(11) NOT NULL auto_increment,
userid int(11) NOT NULL default '0',
name text,
value text,
PRIMARY KEY (id)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;`
For the first three rows i use:
insert into inputlog (userid,name,value) values('$userid','$name','$value')
After that is has to become:
update inputlog set value = '$value' where userid = '$userid' and name = '$name'
where it has to update all the successive rows.
How can i accomplish this?
Too long for comments, so...
Looks like you want to have only 3 rows in your table because you want the data to be sorted by the id. So id=1 will be the latest value, then id=2 and finally id=3.
In short, do not do that, the id field can be any value. Do not code for that. The danger is if you use the id in another table as a foreign key, you will loose referential integrity. What I propose is:
Add an timestamp column for each row.
Every time you insert a new value, set the timestamp column to NOW()
When selecting, sort on the timestamp and limit to 3 results
If you MUST have only 3 rows, you can then delete the row except for the 3 most recent timestamps.
But... if you must do that...
perform a SELECT with the first 2 lines
truncate the table (delete all rows)
insert the new line, then the 2 stored lines
You will then ahve your 3 rows in the order you want. But without seeing the entire reasoning for your application, my "spider sense" tells me you will hit a wall later on...
And check the comments for other things to worry about.
how can i set id primarykey auto_increment same value that automatically generating into my id field will also generate in other field in same table.
How could it possible?
Use mysql_insert_id which returns last auto increment ID...
1) insert into first table, use mysql_insert_id() to get auto increment ID
2) after getting auto increment ID from 1st table, insert on second table with the ID you got.
for more refer http://php.net/manual/en/mysqli.insert-id.php
I have a SQL query as follows-
"INSERT INTO users(id, rank) SELECT v.user, v.vote FROM votes v WHERE
v.assertion = '$ID' ON DUPLICATE KEY UPDATE
rank = ( CASE WHEN v.vote = '1' THEN rank+50 WHEN v.vote = '-1'
THEN rank-200 WHEN v.vote = '3' THEN rank+100 ELSE rank END)"
applied on a database with a table users with and id and rank field, and a votes table with a user and vote field. I have to update the rank of the users in the users table based on their vote.
I really like this kind of query, but I've noticed a problem: every time I execute this from my PHP script the query adds a row to the users table completely empty (with only an ID, which is A_I, and a rank of 1, when usually there would be other field as well). I can't really wrap my head around why this happens.
Any help/idea?
Your table does not have a primary key first provide a primary key to id
run this sql query
alter table user add primary key (id)
and than try it will work
There are two possible reasons :
The id column is not the primary key, and probably you table doesn't have a primary key at all.
Create a primary key like this :
alter table user add primary key (id)
If you insert an value of 0 in an auto increment column, a new id is generated. An auto incremented column must not contain the value 0.
There is also a more general problem with your approach : in fact you only insert the user id and the rank, other compulsory fields in the table (username) are missing. The insert part does not seem to be valid for this reason. If you use an insert on duplicate key update, you must make sure that the result is correct which ever of insert and update is executed.
When I delete the last row in a MySQL table and then insert a new one, why is the id still incremented as though the first weren't deleted? Is there a way to prevent this from happening so it can be as though the original row weren't there? Here's an example
Teachers
id first_name
0 joe
1 mike
2 jim
If I delete "jim" then insert "bob" then bob's id will be 3 and there will be no entry with an id of 2.
Because your id column was configured as autoincremental, and can't have the same value, unless you specify this manually
Deleting any given row will not change the current auto increment value.
You can view the current value of the auto increment variable for the table by running
SHOW TABLE STATUS LIKE 'mytable';
And you can change the auto increment value by running
ALTER TABLE 'mytable' AUTO_INCREMENT = '1234';
you may also use ALTER TABLE tablename AUTO_INCREMENT = 2 if after deleting the row and before inserting the new one, in order to make the id incrementation start at 2
you need to execute this command after every delete operation , this will reset your auto_increment to 1 witch will be set automatically the the last available id ( 2 in your example )
ALTER TABLE table_name AUTO_INCREMENT = 1
I have a db table created like this
CREATE TABLE products(id INT,
name varchar(32),
PRIMARY KEY(id,name),
quantity int,
avail varchar(5) );
If I use the following command on the command prompt, the value is inserted properly:
INSERT INTO products(name,quantity,avail) VALUES('stuffed bear doll',100,'OF_ST');
although the id is duplicated
but when I leave it inside the function like this
$query=sprintf("INSERT INTO products(name,quantity,avail) VALUES('%s',%d,'%s');",
$name,
$quan,
$avail);
mysql_query($query);
then there is no insertion done at all.
You needed to set auto_increment on the id field in your create table syntax. You can edit the column to add it.
Also, if $quan is not valid your SQL syntax will give you an error. Put quotes around it: VALUES('%s','%d','%s')
there is no problem in Your query but i think value of name field is duplicate. As your table structure id-name is primary mean two rows can not have same value of both id and name field. One time one field value can be same but not for both. And here in your table value of id field is always 0 so if in any row value of name field repeat it will not insert that row. And please make id as primary and auto increment so it will be better.
thanks