mysql - php for each loop inserting data twice not each row as intended -
i have associative php array created using json decode function.
i attempting insert array row row database.
the values inserting getting repeats of last row.
php
<?php include "config.php"; $gambatch = $_post["mydata"]; $myjson = json_decode($gambatch,true); foreach ($myjson $row){ //get tweet details $name = $row[0]; $points = $row[1]; } $sql1 = "insert 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"; the json page when dumped php after json decode looks :
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) } } this full array trying insert first 2 values in each row) in code above (eventually want insert kept smaller while getting work).
this array 2 entries dynamic , accept many more code needs flexible enough. think there?
i getting no php errors problem duplicate entries. either replacing or have piece of looping code have not spotted.
many in advance help
finally using prepared statements - using dangerous sql because easy mock up
i got working after further reading. have added prepared statement insert well.
<?php include "config.php"; $gambatch = $_post["mydata"]; $myjson = json_decode($gambatch,true); $mylength= count($myjson); //echo 'length '.$mylength.''; $query = $con->stmt_init(); ($row = 0; $row < $mylength; $row++) { $name = $myjson[$row][0]; $points = $myjson[$row][1]; //$sql1 = "insert testjson(named,points) // values ('".$name."','".$points."')"; $statement = $con->prepare( "insert 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(); i have left old insert may conversion down line somewhere.
a loop required using array row length upper bound. extracted using count($yourarray). above 2 columns , potentially unlimited rows.
the issue have code think can more efficient performing multiple inserts execute inside loop. if can solve switch answer.
Comments
Post a Comment