Home > Net >  Sending data to database sends only one elements instead of six
Sending data to database sends only one elements instead of six

Time:03-10

i try to send elements to my database. It works well but it only sends one element instead of all 6.

My output looks like this: var_dump $unsortiert=

array(6) {
  [0]=>
  string(5) "Test1"
  [1]=>
  string(5) "Test2"
  [2]=>
  string(5) "Test3"
  [3]=>
  string(5) "Test4"
  [4]=>
  string(5) "Test5"
  [5]=>
  string(5) "Test6"
}

My php Code to send the elements "Test 1 to Test6" looks like:

foreach ($unsortiert as $ul) {
  echo $ul;
$ul = "INSERT INTO tagesplan (user) VALUES ('$ul')";
}

When i click on the Button to send the data to the database only Test6 appears. I think the other elements are getting overwrited by "Test 6". But how can i fix this problem to get every value in my database.

<?php




$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}

$unsortiert = $_POST['firstUl'];

echo '<pre>';
var_dump ($unsortiert);
echo '</pre>';

foreach ($unsortiert as $ul) {
  echo $ul;
$sql = "INSERT INTO tagesplan (user) VALUES ('$ul')";
}


if ($conn->query($sql) === TRUE) {
  echo "Tagesplan wurde aktualisiert. Automatische Weiterleitung..."; // Automatische Weiterleitung einbauen
} else {
  echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>

Thanks alot.

CodePudding user response:

Your EXECUTION to insert must exist in foreach loop.

foreach ($unsortiert as $ul) {
  echo $ul;
$ul = "INSERT INTO tagesplan (user) VALUES ('$ul')";
YOUR EXECUTION TO INSERT MUST BE HERE
}

like (PDO example) below

$sql = "INSERT INTO tagesplan (user) VALUES (?)";
$stmt= $pdo->prepare($sql);
foreach ($unsortiert as $ul) {
    $stmt->execute([$ul]);
} 

You should also consider to stop using mysqli and start using PDO.

CodePudding user response:

You only get 1 Test6 entry because in the loop you are overwriting the sql query.

Try it like this

foreach ($unsortiert as $ul) { 
   $sql = "INSERT INTO tagesplan (user) VALUES ('$ul')";
   if ($conn->query($sql) === TRUE) {
     echo "Tagesplan wurde aktualisiert. Automatische 
     Weiterleitung..."; // Automatische Weiterleitung einbauen
   } else {
     echo "Error: " . $sql . "<br>" . $conn->error;
   }
}
    
  • Related