Home > OS >  Split up array value into seperate rows
Split up array value into seperate rows

Time:12-10

I have my 3 arrays which I put into these variables: I have my 3 arrays which I put into these variables:

$title = $_REQUEST['test_bestellte_title'];
$anzahl = $_REQUEST['test_bestellte_anzahl'];
$groesse = $_REQUEST['test_bestellte_groesse'];

I want to insert this array of values into the sql table like

   ID |  Anzahl    | title                 | groesse
-----------------------------------------
    1   |   4      |  Schulkind Shirt gelb |   S
    1   |   5      |  Friends Shirt lila   |   M
    1   |   3      |  Shirt Sesamstraße    |   S    
    1   |   4      |  Shirt Sesamstraße    |   L

But I have no clue how to insert it like shown above

I split them up with for each so far, that's where I'm stuck

   foreach ($anzahl as $einzelanzahl) {
       echo $einzelanzahl['test_bestellte_anzahl'];
   }
   foreach ($title as $einzeltitle) {
       echo $einzelname['test_bestellte_groesse'];
   }
   foreach ($groesse as $einzelgroesse) {
       echo $einzelgroesse['test_bestellte_artikel'];
   }

Thanks in advance!

CodePudding user response:

Assuming the three arrays are always keyed identically, use a single loop:

$arrayOne = array('a', 'b', 'c', 'd');
$arrayTwo = array('w', 'x', 'y', 'z');
$arrayThree = array('m', 'n', 'o', 'p');

foreach ($arrayOne as $key => $valueOne) {
  $valueTwo = $arrayTwo[$key];
  $valueThree = $arrayThree[$key];
  // save your table row to database...
  echo "key: $key one: $valueOne two: $valueTwo three: $valueThree<br/>";
}

/* output:
key: 0 one: a two: w three: m
key: 1 one: b two: x three: n
key: 2 one: c two: y three: o
key: 3 one: d two: z three: p
*/

CodePudding user response:

I mean you can use next peace of code:

<?php

    $title = $_REQUEST['test_bestellte_title'];
    $anzahl = $_REQUEST['test_bestellte_anzahl'];
    $groesse = $_REQUEST['test_bestellte_groesse'];
    
    $query = "INSERT INTO the_table (ID, Anzahl, title, groesse) VALUES (?, ?, ?, ?)";
    $stmt = $pdo->prepare($query);
    
    foreach ($title as $id=>$einzelanzahl) {
        $stmt->execute([1, $title[$i], $anzahl[$i], $groesse[$i]]);
    }

PHP PDO online

CodePudding user response:

If all arrays with the same length:

$title = $_REQUEST['test_bestellte_title'];
$anzahl = $_REQUEST['test_bestellte_anzahl'];
$groesse = $_REQUEST['test_bestellte_groesse'];

$mysqli = new mysqli("localhost","my_user","my_password","my_db");
// Check connection
if ($mysqli -> connect_errno) {
  echo "Failed to connect to MySQL: " . $mysqli -> connect_error;
  exit();
}
$stmt = $mysqli->prepare("INSERT INTO MyTable (`Anzahl`, `title`, 
   `groesse`) VALUES (?, ?, ?)");
for ($i = 0; $i < count($title); $i) {
   // prepare and bind
   $stmt->bind_param($title[$i], $anzahl[$i], $groesse[$i]);
   $stmt->execute();

}

$stmt->close();
$mysqli->close();
  • Related