从mysql获取的数据显示2次

时间:2014-10-15 09:26:14

标签: php mysql sql

我是php的新手。我想从mysql中获取一个特定的数据并将其显示在标签中。我尝试了一个简单的php编码。但是它显示了两次获取的数据(实际上我在名为test的表中创建了2个列,如名称和年龄)请帮助我。这是编码:

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>\n"; 
   } 
?> 

表中的数据是

name=janani
age=25

输出显示为

25
25

3 个答案:

答案 0 :(得分:1)

我确信您有两行具有相同的名称和/或年龄。

为了只显示一个结果,您需要做的是:

  • 使用DISTINCTGROUP BYLIMIT 1

即:

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

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

旁注: 我建议您使用mysqli with prepared statements,因为您的代码对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();

答案 1 :(得分:0)

$ line = mysql_fetch_array($ result); //删除while循环

echo $ line [&#39; age&#39;] [0];

试试这个ans这是从表中获取一个数据的工作..并且可能你的结果显示两次因为$ name在表中匹配两次所以它获取两个记录

答案 2 :(得分:0)

您在数组引用中对'age'进行硬编码,因此它仅回显该元素。按索引循环遍历数组,您也将得到名称。