我有一个使用JSON解码函数创建的关联php数组。
然后,我尝试将这个数组逐行插入到我的数据库中。
值正在插入,但我得到的是最后一行的重复。
<?php
include "config.php";
$gambatch = $_POST["mydata"];
$myjson = json_decode($gambatch,true);
foreach ($myjson as $row){
//get the tweet details
$name = $row[0];
$points = $row[1];
}
$sql1 = "INSERT INTO testjson(named,points)
VALUES ('".$name."','".$points."')";
if(!mysqli_query($con, $sql1))
{
die('Error : ' . mysql_error());
}
if (!mysqli_query($con,$sql1)) {
die('Error: ' . mysqli_error($con));
}
echo '<br><br><br><br><br><br>';
echo "data added";Json在json解码后从php转储时来自另一个页面,如下所示:
array(2) { [0]=> array(7) { [0]=> string(6) "dddddd" [1]=> int(0) [2]=> int(0) [3]=> int(0) [4]=> int(0) [5]=> int(0) [6]=> int(0) } [1]=> array(7) { [0]=> string(7) "fffffff" [1]=> int(0) [2]=> int(0) [3]=> int(0) [4]=> int(0) [5]=> int(0) [6]=> int(0) } } 这是完整的数组,但我只是尝试在上面的代码中插入前两个值)(最终,我希望插入所有的值,但我在使其工作时保持较小的值)。
这也是一个只有两个条目的数组,它最终将是动态的,并接受更多的条目,因此代码需要足够灵活。我想我快到了?
我没有PHP错误,问题是重复的条目。它要么替换自身,要么我有一个循环代码,我没有发现。
非常感谢您的帮助。
最后,我将使用准备好的语句--使用这种危险的sql,因为很容易模拟。
发布于 2015-07-08 18:26:47
经过进一步的阅读,我终于开始工作了。我也增加了准备好的声明,插入。
<?php
include "config.php";
$gambatch = $_POST["mydata"];
$myjson = json_decode($gambatch,true);
$myLength= count($myjson);
//echo 'length is '.$myLength.'';
$query = $con->stmt_init();
for ($row = 0; $row < $myLength; $row++) {
$name = $myjson[$row][0];
$points = $myjson[$row][1];
//$sql1 = "INSERT INTO testjson(named,points)
// VALUES ('".$name."','".$points."')";
$statement = $con->prepare( "INSERT INTO testjson (named,points) VALUES (?,?) ");
$statement->bind_param('si', $name, $points);
$statement->execute();
}
//if (!mysqli_query($con,$sql1)) {
//die('Error: ' . mysqli_error($con));
//}
//echo '<br><br><br><br><br><br>';
//echo "data added";
//}
//mysqli_close($con);
$statement->close();我已经留下了旧的插入,因为它可能有助于转换到线的某处。
需要使用数组行长度作为上限的for循环。这是使用计数($yourArray)提取的。上面是两列和潜在的无限行。
我对代码的唯一问题是,我认为它可以更高效,因为我在循环中执行多个执行插入。如果有人能解决这个问题,我就换个答案。
https://stackoverflow.com/questions/31278988
复制相似问题