A community in which webmasters can ask for help with topics such as PHP coding , MySQL , IT jobs, web design, IT security.
Current location:homephp forumphp talk in 2009 yearsql insert and update question - page 1
User InfoPosts
sql insert and update question#1
I have a form which to insert data into a database. This form takes the content of the fields, and then displays the result page showing the entered information in context. There is a link on this page to edit the user info, which go back to the previous form. Obviously, I do not want duplicate records inserted. Is there an easy way to use an update statement if a record already exists? I am doing this with ajax and php.

posted date: 2009-04-09 01:32:00

Re: sql insert and update question#2
I had made out the solution of this problem. click to view my topic...

hope that hepls.

posted date: 2009-04-09 01:32:01

Re: sql insert and update question#3
MySQL supports the addition of ON DUPLICATE KEY UPDATE to an INSERT statement, which should do what you want.

posted date: 2009-04-09 01:35:00

Re: sql insert and update question#4
Assuming you have a field like (username( or (email(, you could make use of that field to check if a record already exists, if it does, update it.$res = mysql_query("SELECT primary_key FROM my_table WHERE `email` = (" . mysql_real_escape_string($email) . "(");if($row = mysql_fetch_array($res)){ // Record exists, update it $q = "UPDATE my_table SET `username` = (" . mysql_real_escap_string($username) . "( WHERE primary_key = " . (int) $row[(primary_key(];}else{ // Record doesn(t exist, insert $q = "INSERT INTO my_table(username, email) VALUES((" . mysql_real_escape_string($username) . "(, (" . mysql_real_escape_string($email) . "();";}In the above example I assume you have a primary key field that(s an integer (primary_key).

posted date: 2009-04-09 01:38:00

Re: sql insert and update question#5
Why are you not using parameterized queries?

posted date: 2009-04-09 01:42:00

Re: sql insert and update question#6
You should consider using an ORM like http://www.ezpdo.net/blog/?p=2Plain SQL in web applications should only be used if absolutely neccessary, alone for security reason, but also to avoid problems like yours.

posted date: 2009-04-09 02:40:00

select page: « 1 »
Copyright ©2008-2017 www.momige.com, all rights reserved.