Page 1 of 1
PHP mySQL - how to update and/or add
Posted: Tue Feb 02, 2010 11:10 pm
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?
Re: PHP mySQL - how to update and/or add
Posted: Tue Feb 02, 2010 11:42 pm
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.
Re: PHP mySQL - how to update and/or add
Posted: Wed Feb 03, 2010 9:58 am
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);
}
Re: PHP mySQL - how to update and/or add
Posted: Wed Feb 03, 2010 11:55 am
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."' )"; ?>
Re: PHP mySQL - how to update and/or add
Posted: Wed Feb 03, 2010 1:24 pm
by karossii
Thank you, I thought if I didn't specify the fields, it would just insert them in order...