Can you please take a look at following snippets and let me know why I am not able to insert array values into the database. In Js file I have:
<script>
var arr = ["foo", "2015/11/04", "Jill", "Smith", "60"];
var serializedArr = JSON.stringify( arr );
$("#loader").on("click", function(){
var upload = $.ajax({
type: "POST",
url: "loader.php",
data: {array:serializedArr},
cache: false,
beforeSend: function() {
}
});
});
and in PHP file
<?php
define ( 'DB_HOST', 'localhost' );
define ( 'DB_USER', 'root' );
define ( 'DB_PASSWORD', '' );
define ( 'DB_NAME', 'dbapp' );
//$array = json_decode($_POST['array']);
$array = $_POST['array'];
//Open a new connection to the MySQL server
$mysqli = new mysqli('DB_HOST','DB_USER','DB_PASSWORD','DB_NAME');
$arr_one = $mysqli->real_escape_string($array[0]);
$arr_two = $mysqli->real_escape_string($array[1]);
$arr_three = $mysqli->real_escape_string($array[2]);
$arr_four = $mysqli->real_escape_string($array[3]);
$arr_five = $mysqli->real_escape_string($array[4]);
if ($mysqli->connect_error) {
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
//MySqli Insert Query
$insert_row = $mysqli->query("INSERT INTO `models` (name, date, nip, tip, age) VALUES($arr_one, $arr_two, $arr_three, $arr_four, $arr_five)");
if($insert_row){
print 'Success! ID of last inserted record is : ' .$mysqli->insert_id .'<br />';
}else{
die('Error : ('. $mysqli->errno .') '. $mysqli->error);
}
// close connection
$mysqli->close();
?>
I tried both
$array = json_decode($_POST['array']);
and
$array = $_POST['array'];
but I am not able to load the data and even no error message on page?!
$mysqli = new mysqli('DB_HOST','DB_USER','DB_PASSWORD','DB_NAME');to fail$_POST['array']when you process the request?