Updating an ID in the database - php

Database:
Table: news
With the columns: Unique and Primary Key which auto increments called ID, content and title
Code:
-> Creates a form with a textfield, where the user can put in his value for the ID and thus the position of the item
$form->textField("Position of the item item", "id", false, 30, false, getIfExists("id", $originalValues));
-> Posts the new ID as a query to the database
$queryvalues["id"] = $_POST[ "id" ];
It works when I post an ID that isn't in use by another item. However, if I try to overwrite an ID, it gives me an error and doesn't change anything. Obviously, I'd need to update the IDs, so that it'll increment all the conflicting IDs and thus allowing the edited ID to be posted.
I'm kinda annoyed as how to be doing this. I had the idea of adding an index number that defines the position, then switched to sorting the list with the database ID and changing the ID in the CMS will be able to update that whenever the user of the CMS wishes.
However, I'm not too sure how to approach this and whether there is a better option/solution.
Does anyone have any ideas/tips/hints?
I've tried using ON DUPLICATE KEY UPDATE, but I'm having no luck with it so far.
EDIT:
Alright, so ordering works now. I made a new column called Position and just used that to order the items with and it works fine.
However, if I add a new item, with a same position, it'll put it under the other position. So basically the New "0" gets listed under the old "0", while sharing the same key. Any suggestions on how to fix this? I was thinking of incrementing the old duplicate key. But have no idea how this would work exactly.

Don't touch the id column, leave it as it is. Create a new column called "position" and use that, it will then allow non-unique values.
Your ID is setup to always be unique for a reason and having it auto-increment won't help either. Your id column will inevitably have gaps in it when you delete things but this isn't a problem.

"Primary Key" is forced to be unique and permanently persist. It's an identifier of the Entity and not intend to use as sorting/ordering.
to satisfied your requirement, simply add int or datetime/timestamp field then SELECT * FROM yoour_table ORDER BY field_name

I understand that you want to use the ID to ordering your items : don't do that.
Instead, add a new columns named "ordering" :
When INSERT-ing an item, set this field value to the ID value
When UPDATE-ing the item position, swap the position value between the two items that are moving

Related

How can I show results in a select input, based on values shown in a seperate table?

I have three tables, and I'm just looking for a way to make this work.
tbl_campaigns has the columns "id" and "campaign". This one is fairly straight forward, it's just campaign names with an ID number that is auto-incremented so they have unique IDs.
tbl_users has an "id" column so each user has a unique ID number, standard stuff.
tbl_permissions creates a new row whenever a new user is created. This means its "id" column has unique ID values that match to the ID of a user in 'tbl_users'. The columns have been named to match the ID value of a campaign each time a new one is created, for example, the column "campaign_1" is relevant to the campaign in 'tbl_campaigns' with the ID of 1. The idea is this table data is filled with either 1's or 0's.
If a row with the ID of 1 has the number 1 for the column "campaign_1", then the user with the ID of 1 is approved for the campaign with the ID of 1 in the campaign table. If it were 0 then they're not approved for it. The same logic applies for columns "campaign_2", "campaign_3" etc..
Anyways, the issue I'm having is displaying this information on a front-end, as I only want the user to be able to see the campaigns they are approved to run in a drop-down list. When the user is logged in it stores their User ID in a session, I'm not sure if there's a way around it with this method.
Is there any way to get around this? Please note I've done this in procedural PHP as I'm still in my early days, so if anyone has a solution along these lines it would be much appreciated. Sorry if it's a little confusing. I am aware it's a bit ham-fisted, but I just want it to work first.
I believe that your schema needs to be improved, as the table structure should not have to change every time that you add a new campaign.
keep tables tbl_campaigns and tbl_users as they are
create table tbl_permissions with 4 fields (id, user_id, campaign_id and permission)
To check if a user has permission use a query like this:
SELECT permission FROM tbl_permissions WHERE user_id = ? AND campaign_id = ?
So, every time you create a campaign add a corresponding record to the tbl_permissions table. No need to add a new column.
I think the best practice to do this is as follows:
- Create HTML to show to the user(if you don't have it, let me know so i can work on one you can use)
- Create JS archive that will be in charge of calling PHP file and show the result in your HTML(if you don't know how to make it let me know so i can help you)
- Create PHP file, this is going to be in charge of consulting your data base and give the result disired for your select (if you don't know how to make it, let me know)
It is pretty easy to make this work, let me know if you need more help.

Database desing Mysql

currently I found myself wondering if this is the right thing to do in this case.
You see I have a database called for example Warehouse
I this database I have two tables:
[the table items is for saving the items of the system add-modify-delete records]
Items (which its columns are )
TAG_ID
P_NUMBER
QUANTITY
TYPE
LOCATION
DESCRIPTION
REASON
USERID
DATE
[the table lastchanges is for saving the items of the system that has been changed]
lastchanges (which its columns are )
ID
TAGID
PNUMBER
USERID
ACTION
DATING
Now I have been asked to add "exactly what has been changed" to the current form, for example if the quantity changed I have to show that before and after in a bootstrap form.
My brain told me to just add all the columns of the table items into lastchanges and save on those columns the data before changing and into items the new modified data, but performance-wise I see this as a bad action and I want your opinion.
If I understand you correctly you need a history of your DB changes.
If thats the point I would recommend you to create a new row for each entry and soft delete the old one. Then nothing gets lost and you can always get differences or older values.
Adding a the field deleted_at, and created_at as dates would do that trick for you. If deleted_at is null its the current entry, if there is a date set you know exactly when it got "overwritten"

insert a row with one column value based on last record

I need to insert a newly added product in table. But to do so I need to check SKU of last inserted product and increase it by 1 and insert it with new product details. SKU is something like SKUNXXXXX - X is a digit. Changing table structure is not possible.
Possible solutions that I can think of is
Get last row using order by and limit 1.
replace "SKUN" with empty string and increase the number by 1
Insert record with product details and incremented SKU value
But this situation may create a problem(though I am not sure about it). Problem is - what if just after fetching last record and before inserting the new product details, another request comes in and gets the same last record? In this case both of the products have same SKU.
Please let me know how to solve this situation.
One option would be to create an auto increment id column and then use this to create the SKU for each product as it gets inserted. A trigger, which would fire after an INSERT, could then be used to assign the SKU for the newly inserted product. But alas, MySQL does not allow a trigger to modify the table which fired it.
However, there is a potentially easy workaround here. If your SKU values will really always have the format SKUNXXXXX, where XXXXX is some number, then you can simply add an auto increment column, and create the SKU value on the fly when you query for it. So you might create a table called products with the following columns:
CREATE TABLE products
(
id INT(11) NOT NULL AUTO_INCREMENT,
name VARCHAR(55),
...
);
Everytime you do an INSERT on products, the id column will automatically be incremented by MySQL. When you want to get the SKU out, you can simply do a query like this:
SELECT id, name, CONCAT('SKUN', id) AS `SKU`
FROM products
WHERE name = 'someproduct'
If you want the SKU number to not be forever (i.e. once assigned to a given product, it can be reassigned to another new one), then you might consider resetting the auto increment id column, q.v. this SO post for more information.

Magento: how to retrieve deleted tax_class

i have a slight problem here.
i am using stock in the channel with magento, and there plugin uses magento's default tax_class_id.
but the problem we are facing is we have deleted the default magento tax class id.
we have tried to change the plugin to make it use our custom tax_class_id. but as soon we do that plugin dont work.
we have tried to create the same name tax_class but it dont work as it use the new tax_class_id which is now 11.
can we make magento retrieve the deleted tax_class_id?
I don't use Magento, but it sounds like the problem is you deleted a row of data from the tax_class_id table, and when you try to recreate it you get a different value for the auto incrementing primary key tax_class_id, which if I'm correctly reading what you wrote, is confusingly the name of both the table and one of the columns in that table. Not that it matters what they're called, you can go in the tax_class_id table, create a new row, and then double-click on the tax_class_id column to edit the value there to make it match the original value (provided you know what the original value was, of course, but looking in whatever tables reference that value should give you that answer if you don't know). So basically just create it as you've done, it will automatically assign a new counter ID but you can edit that through phpMyAdmin.
Note that, in general, messing with auto incrementing ID values and changing existing data is a good way to mess up your referential integrity, but as long as you have a good backup and understand what you're doing this should work fine for you.

Cannot update the UNIQUE column

I have a categories table like this for my forum:
CREATE TABLE categories (
category_id TINYINT UNSIGNED NOT NULL AUTO_INCREMENT,
name VARCHAR(60) NOT NULL,
PRIMARY KEY (category_id),
UNIQUE (name)
) ENGINE = MYISAM;
As you can see, I set up the name column as UNIQUE because I intended to allow users to freely create new categories as they wish when they create new posts.
Now, I am creating the edit.php page to enable users to edit their own posts, in which I allow them to change the category of the posts if they wish.
Assume that everything goes smoothly with my UPDATE query for the edit.php page.
However, The problem arised here is that when the user accesses the edit.php page to update the his own post's category, he immediately changes his mind that he does not want to change it anymore. The he clicks the submit button. The error occurs saying Duplicate entry 'x' for key y. I guessed that the root cause was at the unique(name) in the table.
So, should I remove the UNIQUE type for the name column and sacrify the feature of allowing users to create new categories freely?
Or, If I can keep it, your help for a piece of code will be appreciated!
Thanks
This is not a database problem which you can solve with SQL. This is an application problem. If no category must be changed or added, the application should not try to change or add categories. Removing the UNIQUE attribute would probably allow the application to do an unwanted change, which doesn't seem to me a great solution.
Anyway, I suggest you use InnoDB. MyISAM does not provide any benefit for this kind of tables.
Add duplicate validation before update the category this is mandatory
For this case append another condition name != '$_POST["name"]' in the update query.
UPDATE categories SET name = '$_POST["name"]'
WHERE category_id = '$_POST["category_id"]'
AND name != '$_POST["name"]'

Categories