How to display certain row's data in a form after clicking edit? (PHP)

半城伤御伤魂 提交于 2020-01-11 13:58:48

问题


enter image description hereI'm new to PHP so please don't judge :D

I'm trying to make table with edit option. No matter in which row I click "Edit" button, only data from last row of the page gets loaded. What should I do?

        $sql = "SELECT * FROM countries LIMIT " . $this_page_first_result . ',' . $results_per_page;
        $result = $connection-> query($sql);

        echo '<div style="text-align:center; font-weight: bold;">';
        for ($page=1; $page<=$num_of_pages; $page++){
            echo '<a href="index.php?page=' . $page . '">' . $page . '</a> ';
        }
        echo '<div><br>';

        if($result-> num_rows > 0){
            while($row = mysqli_fetch_assoc($result)){
                $id = $row['id'];
        $Name = $row['Name'];
        $Area = $row['Area'];
        $Population = $row["Population"];
        $Phone_code = $row["Phone_code"];
                echo "<tr><td><a href='cities.php?id={$row['id']}'>".$row['Name']."</a></td><td>". $row["Area"] ."</td><td>"
            . $row["Population"] ."</td><td>". $row["Phone_code"] ."</td><td><button id='update-button' onclick='openEdit()'>Update</button></td><td><button id='delete-button'>Delete</button></td></tr>";
            }
            print_r($row);
        }
        else{
            echo "</table><h2 style='text-align:center'>There are no countries in the database..</h2>";
        }

    $connection-> close();
    ?>
</table>  
<br>

<div style="text-align:center">
<button type="button" id="close-button-edit" onclick="closeEdit()" style="display:none">Close</button>
<div id="edit_form" style="display:none; text-align:left">
    <form action="edit_country.php" method="POST" class="forms">
        <input type="hidden" name="id" value="<?php echo $id; ?>">
        <p>Name: <input type="text" name="name" required value="<?php echo $Name; ?>"></p>
        <p>Area: <input type="text" name="area" required value="<?php echo $Area; ?>"></p>
        <p>Population: <input type="text" name="population" required value="<?php echo $Population; ?>"></p>
        <p>Phone code: <input type="text" name="phone_code" required value="<?php echo $Phone_code; ?>"></p>
        <input type="submit" name="update" value="Update">
        </form>
</div>

回答1:


There are two strategies that can be used for this problem: all php or using JavaScript.

PHP Only

This requires a submission to pre-fill the edit form. Each update button sends the id as a GET request (it is requesting information, not changing information, so use GET), in the form of an ordinary link, which the php script uses to populate the edit form.

<?php 
// always start with php stuff and don't issue any html until you're done

// initialization
$sortDirection = 'asc';
if(isset($_REQUEST['sortDirection'])) {
    // this decouples the value from user input.  It can only be 'Asc' or 'Desc'
    $sortDirection = $_REQUEST['sortDirection'] == 'asc' ? 'Asc' : 'desc';
}
$rowToEdit = '';
$pdo = new PDO( ... );

// Using PDO because it is more standard
// Leaving connection details to user. See https://phpdelusions.net/pdo_examples/connect_to_mysql for tutorial 
// $pdo is assumed to be the pdo object

// deal with row delete. Destructive, so will be post, and delete button will be set
if(isset ($_POST['delete']) ) {

    // delete from countries where id = ?

    //redirect back to self (Post, Redirect, Get pattern). 
    // Always do this when done working with POST submissions!

    header('Location: /countries.php');
    exit;
}

// deal with row update. This changes data, so use POST
if(isset($_POST['id'])) {

    // update countries set ...

    // redirect back to self
    header('Location: /countries.php');
    exit;
}

// deal with request for row to edit, use GET for info requests 
if(array_key_exists('id', $_GET) {

    $rowToEdit = $pdo->prepare("select * from countries where id = ?");
    $rowToEdit->execute([$id]);
    // fall through to show page
}
// get all country rows (Note, OK to use $sortDirection here because it is decoupled from user input)
$country = $pdo->query("SELECT * FROM countries ORDER BY NAME $sortDirection")->fetchAll(PDO::FETCH_GROUP);

// got all our data, dealt with user input, now we can present the view
?>
<html>
  <head>

  </head>
  <body>
    <h1>Countries</h1>
    <a href="/countries.php?sortDirection=asc">Sort Asc</a>
    <a href="/countries.php?sortDirection=desc">Sort Desc</a>
    <table>
      <tr>
        <th>Name</th>
         <th>Area</th>
         <th>Population</th>
         <th>Phone</th>
         <th></th>
         <th></th>
      </tr>
      <?php foreach( $country as $row): ?>
      <tr>
        <td><a href='cities.php?country_id=<?=$row['id']?>'><?=$row['Name']?></a></td>
        <td><?=$row["Area"]?></td>
        <td><?=$row["Population"]?></td>
        <td><?=$row["Phone_code"]?></td>
        <td> <a href='countries.php?id=<?=$row['id']?>'>Update</a> </td>
        <td>
          <form method="post">
          <input type="hidden" name="id" value="<?=$row['id']?>" />
          <button id='delete-button'>Delete</button>
          </form>
        </td>
      </tr>
    </table>

    <?php if($rowToEdit): ?>

    <div style="text-align:center">
        <form action="countries.php" method="POST" class="forms">
          <input type="hidden" name="id" value="<?= rowToEdit ['id']?>">
          <input type="hidden" name="sortDirection" value="<?= $sortDirection?>">
          <p>Name: <input type="text" name="name" required value="<?= $rowToEdit['Name']?>"></p>
          <p>Area: <input type="text" name="area" required value="<?= $rowToEdit['Area']?>"></p>
          <p>Population: <input type="text" name="population" required value="<?= $rowToEdit["Population"]?>"></p>
          <p>Phone code: <input type="text" name="phone_code" required value="<?= $rowToEdit["Phone_code"]?>"></p>
          <input type="submit" name="update" value="Update">
        </form>
    </div>

    <?php endif; ?>

  </body>
</html>


来源:https://stackoverflow.com/questions/58789096/how-to-display-certain-rows-data-in-a-form-after-clicking-edit-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!