从mysql获取的数据显示2次

I am new to php. I want to fetch a particular data from mysql and display it in the label.I have tried a simple php coding.But it displays the fetched data two times(actually I have created 2 columns such as name and age in a table called test).Please help me.Here is the coding:

displayform.php

<body>
 <form method="post" name="display" action="display.php" >
 Enter the name you like to display the data from MySQL:<br>
<input type="text" name="name" />
<input type="submit" name="Submit" value="display" /> </form> 
</body>
</html>

display.php

<?php 
mysql_connect("localhost", "root", "") or die("Connection Failed");
 mysql_select_db("acp")or die("Connection Failed"); 
 $name = $_POST['name']; 
 $query = "select age from test where name = '$name'";
  $result = mysql_query($query); 
  while ($line = mysql_fetch_array($result)) 
  { 
  echo $line['age'];
   echo "<br>
"; 
   } 
?> 

The datas in table is

name=janani
age=25

The output is displayed as

25
25

$line = mysql_fetch_array($result) ; //remove while loop

echo $line['age'][0];

try this ans this is work for one data fetch from table .. And may possible your result show two time because $name match two times in table so it fetch two record

You are hard coding 'age' in the array reference so it will echo that element only. Loop over array by index and you will get the name also.

I am certain that you have two rows bearing the same name and/or age.

In order to show only one result, what you need to do is:

  • Use either DISTINCT with GROUP BY, or LIMIT 1.

I.e.:

$query = "select DISTINCT age from test where name = '$name' GROUP BY name";

or

$query = "select age from test where name = '$name' LIMIT 1";

Sidenote: I suggest you use mysqli with prepared statements though, since your code is open to SQL injection.

<?php

$DB_HOST = "xxx"; // Replace
$DB_NAME = "xxx"; // with
$DB_USER = "xxx"; // your
$DB_PASS = "xxx"; // credentials

$conn = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($conn->connect_errno > 0) {
  die('Connection failed [' . $conn->connect_error . ']');
}

if($statement=$conn->prepare("select age from test where name = ? LIMIT 1")){

// or this one
// if($statement=$conn->prepare("select distinct age from test where name = ? group by name")){

$name = "janani";

 $statement-> bind_param("s", $name);

// Execute
 $statement-> execute();

// Bind results
 $statement-> bind_result($age);

// Fetch value
 while ( $statement-> fetch() ) {
 echo $age . "<br>";
 }

// Close statement
 $statement-> close();
 }

// Close entire connection
 $conn-> close();