tony
tony

Reputation: 1257

Iterate through arrays and input into database

I have a form with capturing data and posting in an array named "table" so the tables, columns and tuples are linked. I am now trying to iterate through them and seperate them into there individual strings, "$table" = name "$columns" = columns "$columnData" = data

When i do a var_dump on the data, it looks like:-

array (size=2)
0 => 
array (size=3)
  'name' => string 'quote' (length=5)
  'columns' => 
    array (size=3)
      0 => string 'qid' (length=3)
      1 => string 'item' (length=4)
      2 => string 'price' (length=5)
   'data' => 
    array (size=3)
      0 => string '1' (length=1)
      1 => string 'ball' (length=4)
      2 => string '200' (length=3)
 1 => 
array (size=3)
  'name' => string 'rfq' (length=3)
  'columns' => 
    array (size=2)
      0 => string 'id' (length=2)
      1 => string 'item' (length=4)
  'data' => 
    array (size=2)
      0 => string '1' (length=1)
      1 => string 'batt' (length=4)

Which looks in the correct format, although when i try to insert into the database it does not insert, there is something about the $columns variable in the insert statement that does not work. Although I am unsure if i am iterating through the data correctly.

 $AllData = $_POST["table"];
  //  var_dump($AllData)


foreach ($AllData as $sigleData) {

    $table = $sigleData['name'];
    $columns = implode(" ", $sigleData['columns']);
    $columnData = implode(" ", $sigleData['data']);

     $sqlQuery = "INSERT INTO " . $table . " ( " . $columns . ") VALUES( '" . $columnData . "')";

if ($dbConnectionT->query($sqlQuery) == TRUE) {
    echo "database updated";
    echo "</br>";
}
}

So table quote has columns qid, item and price. with values 1, ball and 200 which i am trying to insert correctly into.

Please note, I understand the database violations here, but trying to get the programming example working,

If the previous page is required, please comment. Thanks in advance.

Upvotes: 0

Views: 66

Answers (2)

Sougata Bose
Sougata Bose

Reputation: 31749

Try with -

foreach ($AllData as $sigleData) {

      $table = $sigleData['name'];
      $columns = implode(", ", $sigleData['columns']);
      $columnData = implode(" ',' ", $sigleData['data']);

      $sqlQuery = "INSERT INTO " . $table . " ( " . $columns . ") VALUES( '" . $columnData . "')";

      if ($dbConnectionT->query($sqlQuery) == TRUE) {
        echo "database updated";
        echo "</br>";
      }
}

Upvotes: 1

F2K
F2K

Reputation: 481

In your insert query you are building VALUE part with a single ' for both values... Just change the implode param with "', '"

Upvotes: 0

Related Questions