Skip to content
Advertisement

How to display data inside a single form from database

I am trying to display data from database inside single input form. Let’s say I have 3 rows with column called name.

<input value"<?php echo $row['name']; ?>">

This is how I am getting the rows:

<?php while($row = mysqli_fetch_array($result)) { ?>  <input value="<?php echo $row['username']; ?>">  <?php } mysqli_close($con); ?>

So how do i display the data in one input form instead of three? like in the picture attached. enter image description here

Advertisement

Answer

When you are doing this:

<?php while($row = mysqli_fetch_array($result)) { ?>  <input value="<?php echo $row['username']; ?>">  <?php } mysqli_close($con); ?>

You are essentially creating as many input lines as the loop iterates. Instead you should do this:

<?php $userNames = []; while($row = mysqli_fetch_array($result)) {$userNames[] = $row['username'];} mysqli_close($con); ?>

And now we have a nice $userNames array that we shall implode and put in our input line:

<?php $userNames = implode(",",$userNames);?>
<input value="<?php echo $userNames; ?>">

Don’t use while loops to create the form itself… use them to setup the data….

When creating tables or select form data and such using loops is a good idea if you understand what is going on inside the loop 🙂

There are many more ways to go on this…

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement