-1

Im using javascript ajax to post a value to PHP. In this case, its an object of {x: 5, y, 5}

This will create a proper sql query which results in INSERT.

if (isset($_POST["item"])) {
    $var = $_POST["item"];
    $x = $var["x"];
    $y  = $var["y"];
    $sql = "INSERT INTO hex (id, x, y) VALUES (NULL, $x, $y)";
}

This however, will not work - at all. Why and how can it be fixed ? - thanks

if (isset($_POST["item"])) {
    $var = $_POST["item"];

    $sql = "INSERT INTO hex (id, x, y) VALUES (NULL, $var["x"], $var["y"])";
}

Will not work either:

if (isset($_POST["item"])) {
    $var = $_POST["item"];

    $sql = "INSERT INTO hex (id, x, y) VALUES (NULL, '$var["x"]', '$var["y"]')";
}
C. Finke
  • 129
  • 9

2 Answers2

0

The issue is that you use the " to create a String, and you use it to define your array variable. You cannot combine this. But you can do this to combine strings:

$sql = "INSERT INTO hex (id, x, y) VALUES (NULL, '" . $var["x"] . "', '" . $var["y"] . "')";

Note: that this is not a safe query since MySQL injection will be really easy. Please try to use PDO and parameters. See this answer:

prepared parameterized query with PDO

Community
  • 1
  • 1
Niels
  • 48,601
  • 4
  • 62
  • 81
0

Maybe your problem is caused becasuse of the double quotes.

Try this one:

$sql = "INSERT INTO hex (id, x, y) VALUES (NULL, $var['x'], $var['y'])";

Or even this:

$sql = 'INSERT INTO hex (id, x, y) VALUES (NULL, '.$x.', '.$y.')";
cooper
  • 635
  • 1
  • 8
  • 23