Tags
Asked 3 years ago
17 Jun 2021
Views 248
Johnson

Johnson posted

Display and update MYSQL data via HTML form via PHP

Display and update MYSQL data via HTML form via PHP
sachin

sachin
answered Apr 28 '23 00:00

To display and update MySQL data via HTML form using PHP, you can follow these steps:

Connect to the database using mysqli_connect() function and select the database.


$connection = mysqli_connect("localhost", "username", "password", "database_name");

Retrieve the data from the MySQL database using a SELECT query.


$query = "SELECT * FROM table_name";
$result = mysqli_query($connection, $query);

Loop through the result set and display the data in an HTML table.


echo "<table>";
while ($row = mysqli_fetch_array($result)) {
   echo "<tr>";
   echo "<td>" . $row['column1'] . "</td>";
   echo "<td>" . $row['column2'] . "</td>";
   // add more columns as needed
   echo "</tr>";
}
echo "</table>";

Add an HTML form to the page for updating the data. Use the same column names as in the SELECT query.


<form method="POST" action="update.php">
   <input type="text" name="column1" value="">
   <input type="text" name="column2" value="">
   <!-- add more input fields as needed -->
   <input type="submit" value="Update">
</form>

Create a PHP script to handle the form submission and update the database.

i

f ($_SERVER["REQUEST_METHOD"] == "POST") {
   $column1 = $_POST["column1"];
   $column2 = $_POST["column2"];
   // add more variables for additional columns
   $query = "UPDATE table_name SET column1='$column1', column2='$column2' WHERE id=1";
   mysqli_query($connection, $query);
}

Be sure to replace table_name, column1, column2, and id with the actual names used in your MySQL database.

Finally, close the database connection using the mysqli_close() function.



mysqli_close($connection);

Remember to properly sanitize and validate user input before inserting or updating data in the database to prevent SQL injection attacks. You can use the mysqli_real_escape_string() function to escape any user input used in the query.
Post Answer