Click here to Skip to main content
15,919,749 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I want to insert data into a MySQL database and update if already data exists, but I receive a error. Thanks

What I have tried:

$sql = "INSERT INTO profile (username, fullname, tagline, description, experience, mob, address, workfield) VALUES ('$username1', '$fullname', '$tagline', '$description','$experience','$mob','$address','$workfields') ON DUPLICATE KEY UPDATE fullname = VALUES($fullname), tagline = VALUES($tagline), description = VALUES($description), experience = VALUES($experience), mob = VALUES($mob), address = VALUES($address), workfield = VALUES($workfields)";
Posted
Updated 28-Apr-21 2:45am

1 solution

Probably because you are using string concatenation. If your $description for example contains a quote character, a space, or a comma - which is quiote likely - you will get syntax errors.

Never concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Always use Parameterized queries instead.

When you concatenate strings, you cause problems because SQL receives commands like:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'Baker's Wood'
The quote the user added terminates the string as far as SQL is concerned and you get problems. But it could be worse. If I come along and type this instead: "x';DROP TABLE MyTable;--" Then SQL receives a very different command:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'x';DROP TABLE MyTable;--'
Which SQL sees as three separate commands:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'x';
A perfectly valid SELECT
SQL
DROP TABLE MyTable;
A perfectly valid "delete the table" command
SQL
--'
And everything else is a comment.
So it does: selects any matching rows, deletes the table from the DB, and ignores anything else.

So ALWAYS use parameterized queries! Or be prepared to restore your DB from backup frequently. You do take backups regularly, don't you?

Fix that throughout your whole app, and the problem you have noticed will probably go away at the same time ...
 
Share this answer
 
Comments
Zaid M 28-Apr-21 8:51am    
got it thanks. Can you please tell what changes should I make to the sql query to make it to work? thanks
OriginalGriff 28-Apr-21 9:55am    
https://www.acunetix.com/blog/articles/prevent-sql-injection-vulnerabilities-in-php-applications/#:~:text=Parameterized%20queries%20are%20simple%20to,each%20parameter%20to%20the%20query.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900