【发布时间】:2014-06-07 08:22:51
【问题描述】:
我正在为我正在构建的网站学习 php/mysql。我一切正常,但它非常脆弱和不安全,几乎没有错误陷阱。我已经开始尝试保护我的代码,我要做的第一件事是更好地处理错误并实施准备好的语句以避免 sql 注入。
不幸的是,我遇到了第一个障碍,我最初是这样创建我的 json 数组的:
$myArray=array();
$tempArray = array();
while ( $row = $results->fetch_assoc())
{
$tempArray[0] = $row['unix_timestamp(end_date)'];
$tempArray[0] *= 1000;
$tempArray[1] = $row['bid'];
array_push($myArray, $tempArray);
}
echo json_encode ($myArray, JSON_NUMERIC_CHECK);
这很好地产生了一个 json,然后我可以在我的网站上与 highcharts 一起使用。
我的问题是,我已经更新了我的代码以包含使用 Prepare 和 bind_param 的准备好的语句(通过简单地回显结果进行测试)但是我真的很难将错误放入上述数组中:
while ( $row = $select_stmt->fetch())
{
printf("%s %s\n", $col1, $col2);
//$tempArray[0] = $col2;
//$tempArray[0] *= 1000;
//$tempArray[1] = $col1;
//array_push($myArray, $tempArray);
}
//echo json_encode ($tempArray, JSON_NUMERIC_CHECK);
上面将文本打印出来,但每当我尝试使用 fetch_assoc 时都是另一种选择(我已经做了很多谷歌搜索)我无法让它工作。我总是收到相同类型的错误“调用未定义的方法......”我如何复制我的工作并使用 mysqli 和 bind_result 来生成一个数组?
我希望能准确了解我的问题所在,因为我认为我错过了一个在寻找解决方案时会导致我走上错误道路的概念。
编辑 - 我已经检查并且我正在使用 mysqlnd 驱动程序
更新代码 - 我认为这更接近 - 在再次调用 fetch_assoc 之前使用 get_result 方法而不是“bind_result”。
$result = $select_stmt->get_result();
$myArray=array();
$tempArray = array();
while ( $row = $result->fetch_assoc())
{
$tempArray[0] = $row['end_date'];
$tempArray[0] *= 1000;
$tempArray[1] = $row['bid'];
array_push($myArray, $tempArray);
}
echo json_encode ($tempArray, JSON_NUMERIC_CHECK);
不幸的是,它只检索第一个值,而不是随后的 10 或 100 或 1000 行
解决方案 - json_encode 中的正确数组和 get_result 函数的使用
$result = $select_stmt->get_result();
$myArray=array();
$tempArray = array();
while ( $row = $result->fetch_assoc())
{
foreach ($row as $r){
$tempArray[0] = $row['end_date'];
$tempArray[0] *= 1000;
$tempArray[1] = $row['bid'];
array_push($myArray, $tempArray);
}
}
echo json_encode ($myArray, JSON_NUMERIC_CHECK);
【问题讨论】:
-
感谢没有任何解释的否决票 - 我在这里阅读了一堆答案,但不明白为什么给出答案和/或没有找到适合我的问题的答案。
-
能否再显示一些您收到错误的代码?
-
我最近一次尝试更新了代码 - 但是它只返回一条记录。我不再收到错误消息(我发现我在错误的地方调用函数)。它只是现在如何尝试并在数组中显示结果。我现在正在尝试循环