我有一个server.php文件,应该返回一个整数表。
这些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收集链接到此键的所有int:

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

最佳答案

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

$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

07-28 02:43
查看更多