Good evening ..
I am posting a form with values that include the number of the column in the data base (and not it's name) , so i want to update the field that the column name refers to,
here is my code :
$hours=$_POST['hour'];
$date=$_POST['date'];
$s=$_POST['subject'];
$res=mysql_query("UPDATE study SET [$s] ='$hours' WHERE day='$date' ");
Where $s is an integer that equals the number of the wanted column. But it doesnt work . so is there a way to refer to a column by it's number rather than it's name ?
According to This question, it seems you can only do that by using the information_schema table.
Add an autoincrement column that carries the unique number of the row to an existing table
ALTER TABLE mytable ADD idnum INT NOT NULL AUTO_INCREMENT;
(or add the field in a new table
CREATE TABLE mytable (
idnum INT NOT NULL AUTO_INCREMENT,
... )
And set idnum as PRIMARY KEY.
So that all rows have a unique number created by MySQL automatically. To insert a row, set the field to null and MySQL sets the number automatically
INSERT INTO mytable (idnum, ...) VALUES (null, ...);
Note that you can retrieve the idnum that MySQL set automatically thanks to PHP APIs, eg for mysqli (see this page),
$lastid = $mysqli->insert_id(); // $mysqli being the mysqli object
Then to update a value, you have to store somewhere (preferably in the session rather than on the page [since the user can modify it in this case - unless it doesn't matter])
// Modify field form
...SELECT idnum,nhours FROM mytable WHERE thedate = ...
$_SESSION['idnum'] = $row['idnum'];
...
// Display form ...
// Form processing
// Check first if SESSION has an idnum (an other parameters) in case the user hacked the page and submit a "special" form ...
/// Then
$res=mysql_query("UPDATE study SET nhours='$hours' WHERE idnum=" . $_SESSION['idnum']);
Related
I'm using the following code:
$db = new SQLite3('test.db');
$db->exec("CREATE TABLE IF NOT EXISTS items(id INTEGER PRIMARY KEY, the_id TEXT UNIQUE, type TEXT)");
$db->exec("INSERT INTO items(the_id) VALUES ('abc')");
$db->exec("UPDATE items SET type = 'One' WHERE the_id = 'abc'");
$final = $db->query("SELECT * FROM items");
print_r($final->fetchArray(SQLITE3_ASSOC));
However, I keep receiving a SQLite3::exec(): UNIQUE constraint failed: for $db->exec("INSERT INTO items(the_id) VALUES ('abc')");.
How can I insert new rows into the table?
If the table is empty, the script will run fine and add a new row.
If the table contains 1 record, it will run without errors but a new row won't be added, even when the_id is unique.
If the table contains 1 record and I run it again, it will run with the error mentioned above.
How can I add new rows into this table?
Edit
Just to confirm, I am adding different the_id values and it will only allow for a maximum of 1 in the table for some reason, when the values are unique
It seems you have a second field which must be unique: "id" that is also the primary key.
Either you force the value at every new insert (and must be unique) or you set it as an auto-increment in the table and it gets generated by the dB in an automatic sequence
I suggest the second one: add an AUTOINCREMENT keyword after the id field in table create statement
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.
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;
I'm creating a change log db that's the exact same as my active db except it has a changedate DATE field at the end.
The db is basically one primary key id, and about 50 other columns of various data types. The script I have in php is it tries to insert new ids and if it gets the error message for duplicate primary key, then it should get that row, insert it into my backup db with a curdate() call as the final date value, delete the entry from my first db, then insert the new entry.
I have all the other parts of the script finished except the part where I have to insert everything from the first table + an extra column for curdate(). Or if there's a better solution to my problem of inserting into a backup database when a duplicate primary key comes in when there's a fairly high amount of rows please share that.
You could do an INSERT INTO SELECT:
INSERT INTO `backupTable` SELECT *, NOW() FROM `originalTable` WHERE id = '$id';
You have to specify the ID for the entry you wish to copy to your backup db. You have also to be sure, that the IDis not already in your backup table. You can use REPLACE INTO to workaround this case.
REPLACE INTO `backupTable` SELECT *, NOW() FROM `originalTable` WHERE id = '$id';
basicly, you can create a TIMESTAMP column with CURRENT_TIMESTAMP as default value.
when you insert a row to that table, the current date/time will be automaticly inserted.
is that what you were looking for ?
BTW: i would recommend to kill the problem at it source and make sure a duplicate primary key will not be inserted to the datatable..
to do that, you can use the SELECT LAST_INSERT_ID();
This question already has answers here:
MySQL 'UPDATE ON DUPLICATE KEY' without a unique column?
(3 answers)
Closed 10 months ago.
I'm trying to create more robust MySQL Queries and learn in the process. Currently I'm having a hard time trying to grasp the ON DUPLICATE KEY syntax and possible uses.
I have an INSERT Query that I want to INSERT only if there is no record with the same ID and name, otherwise UPDATE. ID and name are not UNIQUE but ID is indexed.ID isn't UNIQUE because it references another record from another table and I want to have multiple records in this table that reference that one specific record from the other table.
How can I use ON DUPLICATE KEY to INSERT only if there is no record with that ID and name already set else UPDATE that record?
I can easily achieve this with a couple of QUERIES and then have PHP do the IF ELSE part, but I want to know how to LIMIT the amount of QUERIES I send to MySQL.
UPDATE: Note you need to use IF EXISTS instead of IS NULL as indicated in the original answer.
Code to create stored procedure to encapsulate all logic and check if Flavours exist:
DELIMITER //
DROP PROCEDURE `GetFlavour`//
CREATE PROCEDURE `GetFlavour`(`FlavourID` INT, `FlavourName` VARCHAR(20))
BEGIN
IF EXISTS (SELECT * FROM Flavours WHERE ID = FlavourID) THEN
UPDATE Flavours SET ID = FlavourID;
ELSE
INSERT INTO Flavours (ID, Name) VALUES (FlavourID, FlavourName);
END IF;
END //
DELIMITER ;
ORIGINAL:
You could use this code. It will check for the existence of a particular record, and if the recordset is NULL, then it will go through and insert the new record for you.
IF (SELECT * FROM `TableName` WHERE `ID` = 2342 AND `Name` = 'abc') IS NULL THEN
INSERT INTO `TableName` (`ID`, `Name`) VALUES ('2342', 'abc');
ELSE UPDATE `TableName` SET `Name` = 'xyz' WHERE `ID` = '2342';
END IF;
I'm a little rusty on my MySQL syntax, but that code should at least get you most of the way there, rather than using ON DUPLICATE KEY.
id and name are not unique but id is
indexed. id isn't unique
How can I use ON DUPLICATE KEY to
INSERT only if there is no record with
that id and name already set else
UPDATE that record?
You can't. ON DUPLICATE KEY UPDATE needs a unique or primary key to determine which row to update. You are better off having PHP do the IF ELSE part.
edit:
If the combination of name and id IS supposed to be unique, you can create a multi-column UNIQUE index. From there you can use ON DUPLICATE KEY UPDATE.
Why not just use a stored procedure, then you can embed all the logic there are plus you have a reusable piece of code (e.g. the stored proc) that you can use in other applications. Finally, this only requires one round trip to the server to call the stored proc.