0

I want to save an array passed from Ajax to PHP to different columns of the table.

Here are the arrays that Ajax sends to PHP:

I get this on the browser network header after clicking the save button.

Form Data:

tableArray[0][]:awdawd
tableArray[0][]:awdawd
tableArray[0][]:Male
tableArray[0][]:<button class='delete'>Delete</button>
tableArray[1][]:awdaw
tableArray[1][]:awdwa
tableArray[1][]:Female
tableArray[1][]:<button class='delete'>Delete</button>

My problem is after clicking the save button it only saves the name part of the array to the table:

enter image description here

script:

$("#saveTable").click(function(){
 $.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 = $_REQUEST['tableArray'];

    foreach( $tableArray As $v){
    $sql = "INSERT INTO viewTables (name, age, gender, action) VALUES ('$v[0]','$[1]','$[2]','$[3]')";
    $query = $dbc->prepare($sql);
    $query->execute();
    }
?>

2 Answers 2

1

@Sadiq pointed out the problem, which is simply a typo. Let me suggest however that you actually use prepared statements in a better manner, by only preparing the statement once and using parameters to prevent against SQL injection.

$sql = "INSERT INTO viewTables (name, age, gender, action) VALUES (:name, :age, :gender, :action)";
try {
    $sth = $dbc->prepare($sql);
    foreach( $tableArray As $v){
        // bind parameter values
        $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();
    }
} catch (PDOException $e) {
    // something went wrong
    // log an error or whatever
}
Sign up to request clarification or add additional context in comments.

Comments

1
$sql = "INSERT INTO viewTables (name, age, gender, action) VALUES ('$v[0]','$[1]','$[2]','$[3]')";

should be

$sql = "INSERT INTO viewTables (name, age, gender, action) VALUES ('$v[0]','$v[1]','$v[2]','$v[3]')";  // Added array name for the last three values

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.