How do you set allow mySQL to auto increment a row in mySQL when using php? I have set the link_id column as auto_increment using phpMyAdmin but I do not know how to get the row to auto increment when using PDO.
$preparedStatement = $con->prepare('INSERT INTO link (link_id, category, link_desc, link_url) VALUES (:link_id, :category, :link_desc, :link_url)');
$preparedStatement-> execute(array(':link_id' => **AUTO INCREMENT Field in mySQL**, ':category' => $category,':link_desc' => $link_desc,':link_url' => $link_url));
Thanks for the help in advance!
You don't have to do anything special with PHP, but there are several ways in MySQL. One is to use a falsey value or null:
INSERT INTO link (<columns>) VALUES (null, category...
Just exclude the parameter in PHP.
You can also specify columns to insert, and if you leave off the auto_increment key, it gets auto incremented:
INSERT INTO link (category, link_desc...)
You can fill the AUTO_INCREMENT column at INSERT statement with any value ...
MySQL automatically will override AUTO_INCREMENT column value that are defined into your statement and handle with new value correctly.
In console mode it generates a warning if the value wasn't set correctly, but in PHP i think it will be ignored.
Related
I have 2 similar tables. One with an auto increment value and one without. The first table first column is defined as INT(11), PRIMARY UNIQUE INDEX and under EXTRA in phpmyadmin it says AUTO_INCREMENT.
This code does not work and does not add any values.
mysqli_query($con, "INSERT INTO testtable1 VALUES ('', 'zzz', 'yyy')") ;
The second table is the same table with the first column dropped. This code works.
mysqli_query($con, "INSERT INTO testtable2 VALUES ('jjj', 'fff')") ;
Any idea what I am missing? Running 7.2 on the database.
Presumably your testtable1 has a definition reasonably similar to (pseudo-notation):
testtable1
------------
ID INT PK AUTOINCREMENT
SomeColumn NVARCHAR
AnotherColumn NVARCHAR
So when you do this:
INSERT INTO testtable1 VALUES ('', 'zzz', 'yyy')
You're explicitly telling the database to insert an empty string into an INT column. Which won't work.
An AUTOINCREMENT column doesn't need to be told there's an empty value, it will automatically increment. Just specify the values that you are inserting:
INSERT INTO testtable1 (SomeColumn, AnotherColumn) VALUES ('zzz', 'yyy')
Let the database engine handle the ID column. In general it's pretty much always worth explicitly specifying the columns into which you are inserting values or from which you are selecting values. It makes the code easier to read/support and reduces the chance of bugs/errors if the table definition ever slightly changes.
If I am reading this correctly, the first table has an int(11) with AUTO_INCREMENT.
This means you should use similar query as in table 2. As in only pass in values for the two non auto increments fields.
mysqli_query($con, "INSERT INTO testtable1 VALUES ('zzz', 'yyy')") ;
This will work as long as there are 3 fields, the first one is an auto inc int and the other two are strings. This is because auto inc handles the first column automatically.
Also, please check out this link or search for php MySQL predated statements to use prepared statements instead for some safety. It will help you against sql injections.
What I'm asking is whether when inserting a row in a MySQL database the columns that are null need to be included. For instance, when I use phpMyAdmin to insert a row, it will do something like this:
INSERT INTO table
(
`col1`,
`col2`,
`col3`,
`col4`
)
VALUES
(
'value1',
NULL,
NULL,
'value2'
)
Assuming the fields are null by default, can I remove columns and NULL values from the insert statement?
by default, when you create column it is nullable (unless you have set NOT NULL on it). so when you want to insert record for specific columns only, you can omit that column and the values for it are automatically null.
INSERT INTO table (`col1` ,`col4`)
VALUES ('value1','value2')
you can remove them.
if there is a default value - you will get that instead.
If the column name is also omitted, yes: the default value1 will be assumed.
1 NULL is usually - but not always! - the default value for nullable columns. The schema must be consulted to verify this assumption.
I know this may be a stupid question to ask but I have really forgotten how to do it.
How do I auto increment a photo ID whenever a record is inserted into mySQL database ?
I would want it to start with 1 for the first record and then subsequently +1 for the next. Thanks
I have set my database column photoID to PK, NN and AI.
The MySQL documentation for AUTO_INCREMENT has a nice, clear example. In brief, if your field has been defined as auto incrementing, e.g.:
CREATE TABLE tablename (
photoID INT NOT NULL AUTO_INCREMENT,
anotherField VARCHAR(50),
....
);
then when you do an INSERT, if you do not specify a value for photoID, the value will auto increment (if you explicitly specify a value of NULL or 0 in the values list, the value will also auto increment):
INSERT INTO tablename (anotherField) VALUES ('something');
A SELECT would result in photoID value of 1, anotherField value of something.
Set the 'photoID' column on the database to 'autoincrement' using phpmyadmin. It is one of the options on it. It will automatically then do it for you.
CREATE TABLE foto ( ID int auto_increment, UNIQUE(ID) );
I'm creating a messaging system and I'm trying to set it up so it will have a "conversation view" and so users can reply to a message. To do this I have to have a primary ID for each conversation in the table and then a separate unique ID for each message.
My problem is that when I try replying to a message I get this error:
Duplicate entry '98' for key 1
It looks like it isn't allowing me to use the same ID in a column, but I don't have a 'unique' thing set in the table AFAIK.
I also tried to drop the PRIMARY for the id column but got this error:
The message is:
#1075 - Incorrect table definition; there can be only one auto column and it must be defined as a key
I don't understand why it won't let me insert the same ID into the id column, because as you know I need an ID for each conversation.
The mysql_query that I'm using to insert the reply into the table is:
$sql = "INSERT INTO messages (id, message_id, to_user, message, subject, from_user, date, time, date_short)
VALUES ('$id', '$message_id', '$to', '$message', '$subject', '$user', '$date', '$time', '$date_short')";
mysql_query($sql) or die(mysql_error());
Thanks in advance!
Your primary key can not be repeated, otherwise it isn't so useful as a key, is it? The primary key must uniquely identify the record.
The reason you're getting the error is that the column is set to be auto-number. You have not added that column to a separate key, which is a requirement for auto-number columns in MySQL.
Add it to a key/index with that column first, then remove the PK attribute. Make sure you have some PK in the table.
You can't have auto_increment without a key
I suspect you have AUTO_INCREMENT setup on your id field. If this is the case, then the values in the id column must be unique.
Either remove the AUTO_INCREMENT attribute on that column (by redefining the column without AUTO_INCREMENT via an ALTER TABLE command), or don't specify the id value in your INSERT statement.
First, untick AUTO_INCREMENT option on your column and as the second step, try to drop the index again
PRIMARY KEYs are also unique. auto_increment columns must be primary keys. You can't drop PRIMARY KEY from a column without making it not auto_increment.
However, I don't think you should change your table like this. You should keep your IDs and either create a new table with the data you need to update, or use UPDATE instead of INSERT.
Columns with primary keys can't have duplicates, otherwise they lose their uniqueness. MySQL will prevent same values. Having to alter primary key vales is also bad news. You may want to re-approach what you're doing and possibly create more tables.
I found the mysql_insert_id function to retrieve the last auto generated ID.
Should I be using mysql_insert_id +1 to add a new ID or is there a call for adding a new unique ID?
Using NULL for id:
INSERT INTO `database`.`table` (`id`, `user`, `result`) VALUES (NULL, 'Alice', 'green')");
OR not specifying id at all:
INSERT INTO `database`.`table` (`user`, `result`) VALUES ('Alice', 'green')");
Either way works just fine, more of a preference but personally I chose the second as its less typing.
If your id field is set to auto increment, you don't have to add an ID at all. It will be incremented and added automatically.
AUTO_INCREMENT in MySQL does exactly what it sounds like. When you insert a new record it will automatically generate a new ID for you. You do not need a separate call.
Insert a new record and set the auto-increment column to NULL, or just omit it entirely (which is implicitly setting it to NULL - it has the same result). The column will be set to the next auto-increment value instead of NULL.
When you delete a row and you insert again an another row, the new inserted id is not the same as what you delete before you insert again. example you have 3 row and the id value is 1, 2, 3, when you delete 3 then insert again, the id result is 4. And when you try to delete 2, the id result when you try insert again is 5.