我以下列格式param
传递字符串7//3,6
,依此类推...... so it represents a list of events seperated with // and each event has individual items seperated with a comma
我的处理程序首先将其分解为包含7
的单个数组和3,6
然后再次进入包含每个单个数字的单个数组。这些数字将传递给我的Compare类,并返回以下格式的响应:
{"ress":[{"res":[{"ids":"7","ans":null}]},{"res":[{"ids":"3","ans":null},{"ids":"6","ans":"2"}]}
我的问题是,在收到此结果后,我无法确定哪个res
对应于我传递的初始字符串中的哪个事件。为了解决这个问题,我想传递一个我已经在字符串中生成的唯一id,并获取该id作为结果的一部分。所以例如我想传递这样的东西。
(23ddasc)7//(dsefwifw43)3,6
括号中的字符串是唯一ID(它不必采用这种特定格式,我只是用它来说明问题。)然后在结果我想获得这样的东西,以便可以唯一地识别每个事件。
{"ress":[{"res": "uniqueid": "23ddasc" [{"ids":"7","ans":null}]},{"res": "uniqueid": "23ddasc" [{"ids":"3","ans":null},{"ids":"6","ans":"2"}]}
(我知道我没有在这里正确地格式化JSON,我只是插入了uniqueid参数用于说明目的)。我的问题是我应该在我的php代码中进行哪些更改以便能够执行此操作,我已尝试添加response[$uniqueid]
并使我的php代码从括号中提取每个ID并将它们存储在数组中但它根本不起作用。谢谢你的帮助:)
Handler.php
<?php
// get tag
$param= $_POST['param'];
$event = explode("//",$param);
$len = count($event);
$ultresponse["ress"] = array();
for ($x = 0; $x < $len; $x++) {
$ids = explode(",",$event[$x]);
$lens = count($ids);
require_once 'Compare.php';
$db = new Compare();
$response["res"] = array();
for($y = 0; $y < $lens; $y++) {
$result= $db->compimp($ids[$y]);
array_push($response["res"], $result);
}
array_push($ultresponse["ress"], $response);
}
echo json_encode($ultresponse);
?>
&#13;
Compare.php
<?php
class Compare {
function __construct() {
require_once 'DB_Connect.php';
$this->db = new DB_Connect();
$this->db->connect();
}
function __destruct() {
}
public function compimp($ids) {
$conn=mysqli_connect("....");
$result = mysqli_query($conn,"SELECT ids , ans FROM mylist WHERE ids = '$ids'");
$no_of_rows = mysqli_num_rows($result);
if ($no_of_rows > 0) {
return mysqli_fetch_array($result,MYSQLI_ASSOC);
}
}
}
?>
&#13;
答案 0 :(得分:1)
我建议您更改param
变量的格式并使用JSON,这样您就可以来回发送它,如下所示:
的JavaScript :
paramObj = new Array();
data1 = new Array();
data1.push({id: 7});
ids1 = {"uniqueid": "23ddasc", "data": data1};
paramObj.push(ids1);
data2 = new Array();
data2.push({id: 6});
data2.push({id: 2});
ids2 = {"uniqueid": "dsefwifw43", "data": data2};
paramObj.push(ids2);
param = JSON.stringify(paramObj);
// send param to PHP script
你会得到这个JSON:
[
{"uniqueid":"23ddasc","data":[
{"id":7}
]},
{"uniqueid":"dsefwifw43","data":[
{"id":6},
{"id":2}
]}
]
PHP :
<?php
$param = json_decode($_POST['param']);
require_once 'Compare.php';
$db = new Compare();
foreach ($param as &$event)
{
foreach($event["data"] as &$ids)
{
$result = $db->compimp($ids["id"]);
$ids["ans"] = $result["ans"];
}
unset($ids);
}
unset($event);
echo json_encode($param);
这将输出:
[
{"uniqueid":"23ddasc","data":[
{"id":7,"ans":"null"}]
},
{"uniqueid":"dsefwifw43","data":[
{"id":6,"ans":"null"},
{"id":2,"ans":"2"}
]}
]
顺便说一下,在将它发送到SQL之前,不要忘记从GET / POST中获取任何字符串,这样就可以避免任何SQL注入攻击。