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.
Related
I have a MySQL table that has Auto-increment on the ID field. However I need to create, via php, two rows with the same id.
I've tried using $last_id = intval(mysql_insert_id()); But just can't get to set the id on the second row. I am very new to php and SQL has never been my closest friend.
$sql = "INSERT INTO 'table name' (name, age, phone) VALUES ({$name}, {$age}, {$phone});"
$result = mysqli_query($conn, $sql);
Then I would like to run the same insert statement again, maybe with the phone being different, but with the ID being the same.
Your problem here is the auto_increment ID field. This is a primary key, since any auto_increment field must be defined as the table's primary key and therefore cannot have duplicate records.
What you could do is create and additional field for your "ID" field that you want to duplicate and then you can insert normally and leave the auto incrementing field do it's thing.
I have the following database MySQL table.
id (PK, AI)
email
country
lastlogin
I have a regular query in PHP that inserts this into the table.
however, logically, if this code runs several times, the same row will be inserted to the database every time.
I want my reference for checking and duplication to be the email field, and if the email is the same, update the country and the lastlogin.
I checked on other questions for a similar issue and the suggested way was to use ON DUPLICATE KEY like this
INSERT INTO <table> (field1, field2, field3, ...)
VALUES ('value1', 'value2','value3', ...)
ON DUPLICATE KEY UPDATE
field1='value1', field2='value2', field3='value3', ...
However, my primary key is not the email field rather the id but I don't want to run the check on it.
One option is make the email field unique, and then it should behave the same as primary key, at least with regard to MySQL's ON DUPLICATE KEY UPDATE:
ALTER TABLE yourTable ADD UNIQUE INDEX `idx_email` (`email`);
and then:
INSERT INTO yourTable (email, country, lastlogin)
VALUES ('tony9099#stackoverflow.com', 'value2', 'value3')
ON DUPLICATE KEY UPDATE
email='value1', country='value2', lastlogin='value3'
If the email tony9099#stackoverflow.com already exists in your table, then the update would kick in with alternative values.
From the MySQL documentation:
If you specify ON DUPLICATE KEY UPDATE, and a row is inserted that would cause a duplicate value in a UNIQUE index or PRIMARY KEY, MySQL performs an UPDATE of the old row.
This approach doesn't only work with primary keys, it also works with any column having a unique index.
As Dan has mentioned, the ROW_COUNT() in-built function does not support this solution with a standard configuration.
MySQL::ROW_COUNT()
For UPDATE statements, the affected-rows value by default is the number of rows actually changed. If you specify the CLIENT_FOUND_ROWS flag to mysql_real_connect() when connecting to mysqld, the affected-rows value is the number of rows “found”; that is, matched by the WHERE clause.
If modifying the database schema is not an option, you could use the following method:
UPDATE `table` SET `country`='value1', `lastlogin`='value1' WHERE `email`='value3'
IF ROW_COUNT()=0
INSERT INTO `table` (`email`, `country`, `lastlogin`) VALUES ('value1', 'value2', 'value3')
you can use
$query=mysql_query("select * from table where email = 'your email'");
if(mysql_num_rows($query) > 0){
//update
}else{
//insert
}
You can load a row with the given email first and then decide if you have to insert or update depending on the existence of the loaded row. This needs multiple SQL statements, but it can be written in a DBMS vendor independent way. Use a surrounding transaction to handle concurrency. An index on the email-column is useful to keep the existence - check fast. Adding a unique - constraint on the email-column is an option to guarantee that there will never be multiple rows with same email.
You can do it manually like before inserting the value to table first check whether the value exists in table or not if yes then update your related field
$qry = mysql_query("select * from table where email='abc#abc.com'");
$count = mysql_num_rows($qry);
if($count > 0){
write your update query here
}else{
write your insert query here
}
I'm trying to follow along to https://netbeans.org/kb/docs/javaee/ecommerce/connect-db.html this for an assignment but I'm using my own entity relationship diagram in mySQL workbench.
As can be seen here https://www.flickr.com/photos/93791690#N02/23076476850/in/dateposted-public/
But when I try and follow what is said on the Netbeans site Delete 'select * from category' and enter the following SQL statement:
INSERT INTO `category` (`name`)
VALUES ('dairy'),('meats'),('bakery'),('fruit & veg');
But try with my own:
INSERT INTO `book` (`price`) VALUES ('20.0');
INSERT INTO `book` (`author_name`) VALUES ('author_name');
I keep getting errors saying
Error code 1364, SQL state HY000: Field 'author_name' doesn't have a default value
Line 1, column 1
Error code 1364, SQL state HY000: Field 'price' doesn't have a default value
Line 2, column 1
Execution finished after 0 s, 2 error(s) occurred.
Can someone please help me to start going in the right direction
Unless you want to insert two lines,
INSERT INTO `book` (`price`, `author_name`) VALUES ('20.0', 'author_name');
is likely what you want to do. The inserts trying to set just one column are failing because the other column has no default value. All columns which do not have a default value need to be set in an insert. If you intended to insert two rows here, then you'll need to make sure you specify values for both columns in each insert or ALTER your table so that the column has DEFAULT values. For example,
ALTER TABLE `book` MODIFY `author_name` varchar(200) DEFAULT '';
changing the size of the varchar to be whatever your author_name column is and replacing the empty string '' with whatever you want the default to be.
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.
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.