0

I am having problems which the following code:

if(mysql_num_rows(mysql_query("SELECT user_id FROM myTable WHERE user_id = '$user_id'"))){

    mysql_query("UPDATE myTable SET
    id='',
    user_id='$user_id',
    title='$title',
    WHERE user_id='$user_id'
    ") 

}  else {

    mysql_query("INSERT INTO myTable (id, user_id, title)
                 VALUES ('', $user_id, $title) ");
}

The update part seems to work but after the else it doesn't insert the record into the table.

Can anyone spot what could be the problem please?

Satch3000
  • 47,356
  • 86
  • 216
  • 346
  • 1
    If you did some very, very basic error checking, you could find out yourself... [Reference: What is a perfect code sample using the mysql extension?](http://stackoverflow.com/q/6198104) – Pekka Oct 31 '11 at 14:39
  • does mysql_query('query') or die(mysql_error()) say something? –  Oct 31 '11 at 14:42

4 Answers4

2

I am having problems which the following code

no wonder, as this code is just horrible. four nested operators!
even if you'd get some error messages, you'll be unable to tell what operator it belongs to

no errors reported either

you didn't ask for any

make your code more consistent and add error reporting to it:

$sql = "SELECT user_id FROM myTable WHERE user_id = '$user_id'";
$res = mysql_query($sql) or trigger_error(mysql_error()." ".$sql);
if (mysql_num_rows($res)) { 
  $sql = "UPDATE myTable SET id='',user_id='$user_id',title='$title', WHERE user_id='$user_id'";
  mysql_query($sql) or trigger_error(mysql_error()." ".$sql); 
}  else { 
  $sql = "INSERT INTO myTable (id, user_id, title) VALUES ('', $user_id, $title)";
  mysql_query($sql) or trigger_error(mysql_error()." ".$sql); 
}

and you will always be informed of the any error occurred

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
1

Make sure you quote your values in the VALUES () portion:

mysql_query("INSERT INTO myTable (id, user_id, title)
             VALUES ('', '$user_id', '$title') ");
jprofitt
  • 10,874
  • 4
  • 36
  • 46
1

If your ID field an auto increment integer? If so then trying to set it to a value of '' will fail. Just leave the ID out of your insert query altogether and it should work

GordonM
  • 31,179
  • 15
  • 87
  • 129
0

Please look into INSERT... ON DUPLICATE KEY UPDATE, http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html

Derek
  • 4,864
  • 5
  • 28
  • 38
  • Careful with this one if you need to be able to port to another database in the future, few other (if any) databases support it. – GordonM Oct 31 '11 at 14:42