0

I want to show all the names of my tb_app which is currently have (4)names stored and show it on my textboxes...can anyone help me make my code work? I'm just a beginner at programming.

current code:

<html>
<head>
<title>test</title>
</head>
<body>
<?php
include('include/connect.php');
$sql = "SELECT name FROM tb_app";
while($rows = mysql_fetch_array($sql)){
    $name = $rows['name'];
}
?>
Name List: <br />
<input type="text" value="<?php echo $name[0] ?>" /> <br />
<input type="text" value="<?php echo $name[1] ?>" /> <br />
<input type="text" value="<?php echo $name[2] ?>" /> <br />
<input type="text" value="<?php echo $name[3] ?>" /> <br />
</body>
</html>

3 Answers 3

2

Right now you are overwriting the $name variable in each iteration of your loop. You want to treat $name as an array instead, and add an element to the array in each iteration.

Change this:

$name = $rows['name'];

To this:

$name[] = $rows['name'];

You could of course echo your textbox directly inside your while loop as well, and skip the $name variable. However it's good practice to separate your DB or business logic from your display logic, which you are (somewhat) doing. In fact I'd recommend moving your PHP code to the very top of the page, before your opening <html> tag even, and limit how much PHP you mix in with your html.

Sign up to request clarification or add additional context in comments.

Comments

0

A more dynamic way (i.e you have less or more then 4 names):

<html>
<head>
<title>test</title>
</head>
<body>
Name List: <br />
   <?php
       include('include/connect.php');
       $sql = "SELECT name FROM tb_app";

       while($rows = mysql_fetch_array($sql)){
           echo '<input type="text" value="'. $rows['name'] .'" /> <br />';
       }
   ?>
</body>
</html>

Comments

0

You could go even further:

Change name to names:

while($rows = mysql_fetch_array($sql)){
    $names[] = $rows['name'];
}

And then

Name List:

<?php foreach ($names as $name): ?>
  <input type="text" value="<?php echo $name ?>" /> <br />
<?php endforeach; ?>

Comments

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.