0

I am having some troubles on generating a page that can print a form based on the SQL query. In this case, what I need is to perform a query to list all the rows of the table where the name is Porcac1x. The content needs to be input fields that show current variable value and that can be updated. This is exactly where I get stuck. How can I create a form which is variable based on the php while loop? With the attached code I am able to list the content and show all the variables but I am having troubles on creating the form action to update the values. I'd like to make clear that I don't care about the security as the code will run in a local environment where I am the only one having access.

This is current outputenter image description here however the save button of course doesn't work

<html>
 <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="description" content="$1">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="stylesheet" type="text/css" href="style.css">

    <title>test page</title>
</head>
    
    <body><form action="" method="post">
        <?php
        
        
                                $servername = "localhost";
                                $username = "root";
                                $password = "root";
                                $dbname = "root";

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

                                $sql = "SELECT `id`, `title`, `amount` FROM `expenses` WHERE name='Porcac1x';";
                                $result = $conn->query($sql);

                                if ($result->num_rows > 0) {
                                  // output data of each row
                                  while($row = $result->fetch_assoc()) {
                                    echo "ID: <input type='text' name='".$row["id"]."' value='".$row["id"]."'> Title: <input type='text' name='".$row["title"]."' value='".$row["title"]."'> Amount: <input type='text' name='".$row["amount"]."' value='".$row["amount"]."'> <button type='submit' name='save'>Save</button><br>";
                                  }
                                } else {
                                  echo "0 results";
                                }                               
                                

                              
                                   if(isset($_POST['save'])){
                                       
                                    $myID = $_POST["id"];//??? < Issue
                                    $myTitle = $_POST["title"];//??? < Issue
                                    $myAmount = $_POST["amount"]; //??? < Issue
                                    
                                    echo $myID;
                                    echo $myTitle;
                                    echo $myAmount;
                                       
                                       $sqlUpdate = "UPDATE expenses SET title='$myTitle', amount ='$myAmount' WHERE id='$myID';";
                                       
                                       echo $sqlUpdate;
                                       
                                        if ($conn->multi_query($sqlUpdate) === TRUE) {
                                            echo "Record updated successfully";
                                          $risposta= "Record updated successfully";
                                        } else {
                                          echo "Error updating record: " . $conn->error;
                                           $risposta= "Error updating record: " . $conn->error;
                                        }

                                        $conn->close(); 
                                   }                                        
                                   
                                ?>
                            </form>
                                
                                </body>
                                </html>

10
  • You're missing a form element... To this, you'd either have echo a whole form per row or use the array notation for the name elements on your inputs (<input type="text" name="element_name[]" value="value">). Commented Jun 21, 2020 at 16:32
  • What a miss! Thanks @MartijnICU! Commented Jun 21, 2020 at 16:33
  • I kind of assumed this wasn't meant for production but @Dharman is absolutely right. This shouldn't be used in real life. Commented Jun 21, 2020 at 16:42
  • @MartijnICU I doesn't matter whether this is production code or just for you. Buggy code like this should never be written or used in any way Commented Jun 21, 2020 at 16:43
  • I want to agree, but everyone starts somewhere... no one writes safe code on their first try. I could also say that it's bad practice to keep your business logic in the same file as your view. But this looks like some one making their first steps into PHP. (no offence @Porcac1x) Commented Jun 21, 2020 at 16:46

1 Answer 1

1

Like I said in the comments for this to work, you'll need the array notation. (Or 1 form per row)

This is the solution for 1 form element per row:

<html>
 <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="description" content="$1">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="stylesheet" type="text/css" href="style.css">

    <title>test page</title>
</head>

 <body>                 
     <?php

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

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

        $sql = "SELECT `id`, `title`, `amount` FROM `expenses` WHERE name='Porcac1x';";
        $result = $conn->query($sql);

        if ($result->num_rows > 0) {
            // output data of each row

            while($row = $result->fetch_assoc()) {
                echo '<form method="post">';
                echo "ID: <input type='text' name='id' value='".$row["id"]."'> Title: <input type='text' name='title' value='".$row["title"]."'> Amount: <input type='text' name='amount' value='".$row["amount"]."'> <button type='submit' name='save'>Save</button><br>";
                echo '</form>';
            }
        } else {
            echo "0 results";
        }

        if(isset($_POST['save'])){

            $myID = $_POST["id"];//??? < Issue
            $myTitle = $_POST["title"];//??? < Issue
            $myAmount = $_POST["amount"]; //??? < Issue

            echo $myID;
            echo $myTitle;
            echo $myAmount;

            $sqlUpdate = "UPDATE expenses SET title='$myTitle', amount ='$myAmount' WHERE id='$myID';";

            echo $sqlUpdate;

            if ($conn->multi_query($sqlUpdate) === TRUE) {
                echo "Record updated successfully";
                $risposta= "Record updated successfully";
            } else {
                echo "Error updating record: " . $conn->error;
                $risposta= "Error updating record: " . $conn->error;
            }

            $conn->close();
        }



        ?>
    </body>
</html>
Sign up to request clarification or add additional context in comments.

7 Comments

Thanks for this code, it looks like the variables myID, myTitle and myAmount are still empty
I've edited the answer, removing the variable names on the inputs. This should work as expected.
Not yet I am afraid, the three variables now have 'Array' as value
And in those arrays you'll find your values.. If you want to treat each row as a single update you should add the form element in your while loop and remove the []
Humm if I do that it seems that what ever button I press only the last row is updated
|

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.