skip to Main Content

I retrieve data with the post method as below

$no_wa1= $_POST['no_wa'][0];
$no_wa2= $_POST['no_wa'][1];
$no_wa3= $_POST['no_wa'][2];

then I want to display the data above with a while loop and a for loop

I want to enter it into the database

2

Answers


  1. Let me help you step by step. Following is the HTML file which has form and 3 inputs.

    <form method="POST" action="your_script.php">
        <input type="text" name="no_wa[]" placeholder="Enter number 1">
        <input type="text" name="no_wa[]" placeholder="Enter number 2">
        <input type="text" name="no_wa[]" placeholder="Enter number 3">
        <button type="submit">Submit</button>
    </form>
    
    

    You have not mentioned whether you have setup the DB connection or not, so this code is to establish a Database connection.

    <?php
    // Database connection
    $servername = "your_server";
    $username = "your_username";
    $password = "your_password";
    $dbname = "your_database";
    
    $conn = new mysqli($servername, $username, $password, $dbname);
    
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    
    

    Retrieve Form Data so that you can use that variable in your loops

    
    
    // Retrieve data from POST request
    $no_wa = $_POST['no_wa'];
    
    // Prepare the SQL statement
    $stmt = $conn->prepare("INSERT INTO your_table (number) VALUES (?)");
    
    if ($stmt === false) {
        die("Prepare failed: " . $conn->error);
    }
    
    
    

    Insert data in Database by using While Loop:

    $i = 0;
    while ($i < count($no_wa)) {
        $number = $no_wa[$i];
        $stmt->bind_param("s", $number); // "s" indicates the type is string
        if ($stmt->execute() === TRUE) {
            echo "New record created successfully using while loop<br>";
        } else {
            echo "Error: " . $stmt->error . "<br>";
        }
        $i++;
    }
    
    

    Insert data in Database by using For Loop:

    for ($i = 0; $i < count($no_wa); $i++) {
        $number = $no_wa[$i];
        $stmt->bind_param("s", $number); // "s" indicates the type is string
        if ($stmt->execute() === TRUE) {
            echo "New record created successfully using for loop<br>";
        } else {
            echo "Error: " . $stmt->error . "<br>";
        }
    }
    
    

    Close the Statement and Connection:

    $stmt->close();
    $conn->close();
    
    
    Login or Signup to reply.
  2. Something like that would probably do what you want :

    foreach ($_POST['no_wa'] as $no_wa) {
        // whatever action you want
        echo "$no_wan";
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search