PHP mySQL - how to update and/or add

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
karossii
Forum Newbie
Posts: 5
Joined: Sat May 30, 2009 6:11 am

PHP mySQL - how to update and/or add

Post by karossii »

I am trying to run a function that tests if a variable inputted by the user matches a record in the mySQL database (a column where it is forced unique, so only 1 match if any)... and if it does match I want to run an UPDATE query; if no matches are returned, I want to run an INSERT query.

What is the easiest/best way to do this?
pbs
Forum Contributor
Posts: 230
Joined: Fri Nov 07, 2008 5:31 am
Location: Nashik, India
Contact:

Re: PHP mySQL - how to update and/or add

Post by pbs »

Check the database field value with value inputted my user like this

Code: Select all

 
$sql = "select * from TABLENAME where FIELDNAME = USERVALUE ";
 
if it returns any records then run UPDATE query else run INSERT query.
karossii
Forum Newbie
Posts: 5
Joined: Sat May 30, 2009 6:11 am

Re: PHP mySQL - how to update and/or add

Post by karossii »

So would that be something like this?

{assuming here that the table name is 'tabledata', there are three fields, 'myfield', 'field1', and 'field2'}

Code: Select all

$query = [color=#FF0000]"SELECT * FROM tabledata WHERE myfield = '"[/color] . $userinput . [color=#FF0000]"'"[/color];
$update = [color=#FF0000]"UPDATE tabledata SET field1 = '"[/color] . $field1 .[color=#FF0000] "', field2 = '"[/color] . $field2 . [color=#FF0000]"' WHERE myfield = '"[/color] . $userinput . [color=#FF0000]"'"[/color];
$insert = [color=#FF0000]"INSERT INTO tabledata  '"[/color] . $userinput . [color=#FF0000]"','"[/color] . $field1 . [color=#FF0000]"','"[/color] . $field2 . [color=#FF0000]"'"[/color];
 
$findData = [color=#0000FF]mysql_query[/color]($query);
 
if ($findData !=[color=#FF0000]''[/color]){
 
    $updateData = [color=#0000FF]mysql_query[/color]($update);
 
} else {
 
    $updateData = [color=#0000FF]mysql_query[/color]($insert);
}
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Re: PHP mySQL - how to update and/or add

Post by social_experiment »

Code: Select all

<?php $insert = "INSERT INTO tabledata  '" . $userinput . "','" . $field1 . "','" . $field2 . "'"; ?>
should be

Code: Select all

<?php $insert = "INSERT INTO tabledata ( field1, field2, field3 ) VALUES ( '".$userinput."', '".$field1."', '".$field2."' )"; ?>
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
karossii
Forum Newbie
Posts: 5
Joined: Sat May 30, 2009 6:11 am

Re: PHP mySQL - how to update and/or add

Post by karossii »

Thank you, I thought if I didn't specify the fields, it would just insert them in order...
Post Reply