0

I am very new in php and mysql and I am trying to add a product to a cart. I think my code works fine except the part "quantitat+1". (If I just replace this for a number it works) I don't know how should I say that I want to update and add 1 the existing quantity whatever it is.

I get no error, so I don't know what's the problem. I tried ($row['quantitat'];)+1 and it doesn't work either

I'm an absolute beginner, so I suppose I'm making a very obvious mistake or there is something I don't understand.

if(isset($_GET["id"])) {
    $result = mysql_query("SELECT * FROM carret 
                            WHERE producte='".$_GET["id"]."'");
    }

if (mysql_num_rows($result)>0) { // if already there is one or more
    mysql_query("UPDATE carret SET quantitat = quantitat + 1
    WHERE producte='".$_GET["id"]."'");
    echo "UPDATE. I have added 1";
}else{
    mysql_query("INSERT INTO carret (producte, quantitat)
    VALUES (".$_GET["id"].",1)");
    echo "INSERT. I have inserted one new product";
    }
Nrc
  • 9,577
  • 17
  • 67
  • 114
  • Your script is vulnerable to SQL Injection – Baba Oct 12 '12 at 11:08
  • 4
    @Baba: That's an incredibly helpful comment for someone who says they are "*very new in php and mysql*"! Narcis, what Baba meant to say was that you should read the story of [Bobby Tables](http://stackoverflow.com/questions/332365/xkcd-sql-injection-please-explain) to understand about a major vulnerability in the way that you have written your code. You should use instead [prepared statements](http://stackoverflow.com/a/60496/623041), into which you pass your variables as parameters that do not get evaluated for SQL. – eggyal Oct 12 '12 at 11:11

1 Answers1

0

Can you try the following

$mysqli = new Mysqli("localhost", "username", "password", "database");

if (isset($_GET["id"])) {
    $id = $mysqli->real_escape_string($_GET["id"]);
    $mysqli->query("INSERT INTO carret (producte, quantitat)VALUES ('$id',1) ON DUPLICATE KEY UPDATE quantitat = quantitat+1; ");
}
Baba
  • 94,024
  • 28
  • 166
  • 217
  • This creates a new row. It does not recognize the duplicate. I don't know if I'm doing something wrong? – Nrc Oct 13 '12 at 15:09
  • @narcis you need to set `producte` as `primary ID` – Baba Oct 13 '12 at 15:10
  • Sorry, I don't know how to do that. I'm confused. I thought that the primary key was the id? I'm looking for documentation and I find that there should be just one primary key in each table? – Nrc Oct 13 '12 at 15:34