Php backend website user entering data

Is it possible to have a number automatically generated and displayed on and updateProducts page a user is adding information to. This number I would assume would come from mysql database. I am sure it would be possible. But how tricky is it?

Wait… I have discovered more. If I input a product number that has been previously used it returns an error stating the number has been used before. I realise this is because I have set this field up as a primary key in my database.

What php validation code can I use that will bring up an error for the user rather than the nasty looking fatal error.

Hope this makes sense and I appreciate your time.

1 Like

It is usual to have an ID column which is “Auto Increment”.
If the number is a product number, as in from a catalogue (Eg. JF4321), you would have to query from the database and check if it’s there before inserting.

Yes, PKs must be unique.

If they truly should be unique you could use INSERT IGNORE
No error, - but - you may want to check success / fail on the attempts.

As SamA74 posted, auto-increment Id field are often used as PKs

But they are not always needed, nor always the best way to do it. eg.

If I have a table with
city_name
state_name
population
per_capita_income

None of those fields alone would be likely to be unique, but a combination of city_name and state_name would be.

That makes a good primary key without needing an auto increment if field.

No need to check if it exists before trying to insert though - just look for a 1062 error being returned from the insert in order to take the required alternate action for if it does exist.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.