在PHP SQL查询中使用JSON问题

时间:2016-04-05 07:19:20

标签: php mysql json

我有一个server.php文件,它应该返回一个int表。 这些int中的每一个都与一个键相关联(一些int可以具有相同的键)。该表只需包含链接到特定键的int。

要获得其中一个密钥,我需要另一个密钥作为参数。

所以过程是:

服务器由$ http.post调用(我正在使用AngularJS):

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

(尚未使用serverFlag,而parameterKey是一个字符串)

然后我使用parameterKey来获取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();

然后,我使用anotherKey收集链接到此密钥的所有内容:

$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);

(我不知道到目前为止我是否已经非常清楚了......)

运行此代码时出现JSON错误:

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

我不确定错误在哪里。有什么想法吗?

修改

我有以下错误:

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();)

1 个答案:

答案 0 :(得分:0)

您正在以错误的方式插入字符串:

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

请注意您是如何直接致电$objData->data的。你应该这样做:

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

在PHP中,您只能在字符串中插入变量。如果要引用对象属性或数组项/字典键,则必须将它们括在{}中。所以这是有效的:

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

这是有效的:

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

虽然不是这样:

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

编辑:在更安全的注释上,您永远不应该从输入直接向查询提供任何内容,因为您将自己暴露给安全威胁(SQL注入)。考虑使用prepared statements

相关问题