-4

Here is my code:

if (isset($_GET['id']) && !empty($_GET['id'])) {
    $deal_update_sql = "UPDATE mydb.nl_dailydeals SET storeid = '5', cultureid = '10' WHERE product_id = ".$_GET["id"];
    $result = mysql_query($deal_update_sql);
}
else {
    $insert_query = "INSERT INTO admin_zuki_be.nl_dailydeals (product_id, storeid) VALUES (3, 2)";
    $result = mysql_query($insert_query);
}

This code doesn't work. No matter what id I pass within the URL through GET, it should be inserted into the database. If the id is already present in the database, then it should update the record with the given id.

How can I fix this?

MC Emperor
  • 22,334
  • 15
  • 80
  • 130

2 Answers2

0

use the line:

 $result = mysql_query($deal_update_sql) or die(mysql_error());

which, if the query fails, will tell you what the error was. Take the die() out of production code though.

I suspecy your issue is that you arte trying to update a record that doesnlt exist. You need to check if the product_id exists, if it does then update it, if it doesnlt insert it.

Horaland
  • 857
  • 8
  • 14
0

Three important points :

  1. Your code is very vulnerable to SQL injection, since you did not sanitize your input. Use mysqli_real_escape_string to sanitize input before using it in the query.

     $id = mysqli_real_escape_string($link, $GET['id']); //Link will be your connection variable
    
  2. mysql_* functions are deprecated. Do not use them. Use mysqli_* functions instead.

  3. The logic is wrong.

     if (isset GET id) {
      check if id exists in db using select query
      If  (id exists in db)
            update query
      else 
            insert query
    }
    

The code will be :

   if (isset($_GET['id']) && !empty($_GET['id'])) {
       $id = mysqli_real_escape_string($link, $GET['id']); //Link will be your connection variable
       $query = "SELECT product_id FROM mydb.nl_dailydeals WHERE product_id=". $id;
       if ($result = mysqli_query($link, $query)) {
              //run your UPDATE query
        } else {
            // run your insert query
        }
janenz00
  • 3,315
  • 5
  • 28
  • 37