Reputation: 135
I have a script that gets the contents of a table that i added.
And i want to do is save the content into a database.
In the picture the table and the content of my dataSet variable that i get from the table.
i check the dataSet and alert it to check if it has value.
My problem is im having trouble saving the array that i passed to php cause its not working its not saving. I got an error in my saveTable.php invalid argument foreach.
script:
var names = [].map.call($("#myTable2 thead th"), function (th) {
return $(th).text();
});
var x = [].map.call($("#myTable2 tbody tr"), function (tr) {
return [].reduce.call(tr.cells, function (p, td, i) {
p[names[i]] = $(td).text();
return p;
}, {});
});
var dataSet = JSON.stringify(x);
alert(dataSet);
$.ajax(
{
url: "saveTable.php",
type: "POST",
data: { tableArray: dataSet},
success: function (result) {
}
});
saveTable.php
<?php
error_reporting(-1);
ini_set('display_errors', 'On');
$host = "localhost";
$user = "root";
$pass = "";
$db = "test";
$dbc = new PDO("mysql:host=" . $host . ";dbname=" . $db, $user, $pass);
$dbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$tableArray = isset($_REQUEST['tableArray']) ? $_REQUEST['tableArray'] : "";
$sql = "INSERT INTO viewTables (name, age, gender, action) VALUES (:name, :age, :gender, :action)";
$sth = $dbc->prepare($sql);
foreach( $tableArray As $v){
$sth->bindValue(':name', $v[0], PDO::PARAM_STR);
$sth->bindValue(':age', $v[1], PDO::PARAM_STR);
$sth->bindValue(':gender', $v[2], PDO::PARAM_STR);
$sth->bindValue(':action', $v[3], PDO::PARAM_STR);
$sth->execute();
}
?>
new error:
Upvotes: 0
Views: 1420
Reputation: 2020
You have to convert the string to an array using json_decode
to be able to use it as an array.
Upvotes: 0
Reputation: 1961
It looks that you are trying to use a String
type in the foreach
loop. Try:
$tableArray = isset($_REQUEST['tableArray']) ? json_decode($_REQUEST['tableArray']) : array();
This should make it work. Good luck, hope this helps!
Upvotes: 1