简体   繁体   中英

Issue with JSON in a PHP SQL query

I have a server.php file which is supposed to return a table of ints. Each one of these ints is linked to a key (some ints can have the same key). The table needs to only contain ints linked to a specific key.

To get one of these key, i need to have another key as a parameter.

So the process is :

The server is called by an $http.post (i'm using AngularJS) :

$http.post('server.php', {"data" : parameterKey, "serverFlag" : 4})

(serverFlag is not yet used, and parameterKey is a string)

I then use parameterKey to get anotherKey :

$data = file_get_contents("php://input");
$objData = json_decode($data);

$conn = new PDO(/*something*/);
$outp = [];

$anotherKey  = $conn->query("SELECT anotherKey FROM myTable1 WHERE parameterKey = $objData->data");
$anotherKey  = $anotherKey ->fetch();

Then, i use anotherKey to gather all the ints linked to this key :

$result = $conn->query("SELECT myInt FROM myTable2 WHERE id = $anotherKey  ORDER BY myInt ASC");
while($rs = $result->fetch()) {
        if ($outp != "") {
            array_push($outp,$rs["myInt"]);
        }
}

$outp =json_encode($outp);
echo($outp);

(I don't know if I have made myself very clear so far...)

So i have a JSON error when running this :

Error: JSON.parse: unexpected character at line 1 column 1 of the JSON data

I'm not really sure where the error is. Any ideas ?

EDIT

I have the following error :

Fatal error: Call to a member function fetch() on boolean in C:\wamp64  \www\tests\server.php on line <i>47</i> 
(line 47 =  $anotherKey  = $anotherKey ->fetch();)

You are interpolating the string the wrong way:

$anotherKey  = $conn->query("SELECT anotherKey FROM myTable1 WHERE parameterKey = $objData->data");

Note how you are calling $objData->data directly. You should do this instead:

$anotherKey  = $conn->query("SELECT anotherKey FROM myTable1 WHERE parameterKey = {$objData->data}");

In PHP you can only interpolate variables in a string. If you are referring to object properties or array items/dictionary keys, you have to enclose them in {} . So this is valid:

$myInterpolatedString = "This is a string with a $variable";

and this is valid:

$myInterpolatedString = "This is a string with a {$object->property}";

while this is not:

$myIncorrectlyInterpolatedString = "This is a string with $object->property";

Edit: on a more security oriented note, you should never feed anything from the input directly to a query, since you are exposing yourself to a security threat (SQL injection). Consider using prepared statements !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM