0

I have code that looks like this:

    $fields = $_POST;

    $valueStrings = array();

    foreach ($fields as $key => $value) {
        array_push($valueStrings, $key . "=" . (string) $value);
        // I also tried "$key = $value"

    }

    $updateRowQuery = "UPDATE ShoppingCart
                       SET " . implode(',', $valueStrings) . "
                       WHERE cartID = $cartID";

I get the error:

Invalid query: Unknown column 'test' in 'field list', query is: 
UPDATE ShoppingCart
SET shipToSameLocation=1,shipToSameLocation_shippingLocationID=5,shipToSameLocation_shippingMethod=test
WHERE cartID = 1405

If I remove the shipToSameLocation_shippingMethod field, it works fine. We can see that its value test (other values, too) don't have quotes around despite the (string) casting in the loop.

How can I fix this?

Dan P.
  • 1,707
  • 4
  • 29
  • 57
  • 1
    Your code is susceptible to SQL Injection: http://stackoverflow.com/a/60496/507793 – Matthew Mar 17 '15 at 20:55
  • Your concatenation is already a string. Your query is also just a string. Casting a string to a string doesn't magically add quotes around it. You should also use mysqli or pdo and bind your queries. – Jonathan Kuhn Mar 17 '15 at 20:57
  • The company website I'm working on was made in like 2005 and has me using the first MySQL driver for now. The post doesn't seem to cover that driver, but I'll check around on how to make it more secure still. Thanks – Dan P. Mar 17 '15 at 20:58
  • Added an edit, but I also tried simply "$key = $value" – Dan P. Mar 17 '15 at 20:59
  • You _must_ limit the keys to just the columns in the table. If you don't all sorts of mayhem could happen. – Rick James Mar 17 '15 at 21:04
  • MySQL thinks `test` is a column but `test` is a value: shipToSameLocation_shippingMethod=test, and I want to find out how can MySQL make test a string / put quotes around the value. – Dan P. Mar 17 '15 at 21:33

1 Answers1

0

Wrap all values in quotes. You're unnecessarily casting stuff there. MySQL will figure it out for you.

jdu
  • 581
  • 2
  • 3