Php 从mysql获取的数据显示2次
我是php新手。我想从mysql中获取一个特定的数据并将其显示在标签中。我尝试了一个简单的php编码。但是它显示了两次获取的数据(实际上我在一个名为test的表中创建了两列,如name和age)。请帮助我。以下是编码: displayform.phpPhp 从mysql获取的数据显示2次,php,mysql,sql,Php,Mysql,Sql,我是php新手。我想从mysql中获取一个特定的数据并将其显示在标签中。我尝试了一个简单的php编码。但是它显示了两次获取的数据(实际上我在一个名为test的表中创建了两列,如name和age)。请帮助我。以下是编码: displayform.php <body> <form method="post" name="display" action="display.php" > Enter the name you like to display the data f
<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>
输入要显示MySQL数据的名称:
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
name=janani
年龄=25
输出显示为
25
25
25
25
$line=mysql\u fetch\u数组($result)//删除while循环
echo$行['age'][0]
尝试此操作。这是从表中提取一次数据的工作。。您的结果可能会显示两次,因为$name在表中匹配了两次,所以它会获取两条记录您正在数组引用中硬编码“age”,所以它只会回显该元素。通过索引循环数组,您也将获得名称。我确信您有两行具有相同的名称和/或年龄 为了只显示一个结果,您需要做的是:
- 将
与DISTINCT
一起使用,或使用groupby
LIMIT 1
旁注:我建议您使用,因为您的代码是开放的
您确定测试
表中只有一个janani
吗?您确定没有重复的数据吗?如果是,请在查询中添加LIMIT 1
和/或DISTINCT
;并找到结果行数..作为一个状态器,您不应该盲目依赖结果..按照过程查看您要获取的行数您可能有两次janani名称。因为代码运行得非常好。请检查您的数据库。这并不能解释为什么数据显示两次。这仅在结果中只有一行时有效。如果他试图显示多行(除了他报告的重复,这应该是固定的)?@simone yup我提到过。我认为用户查询是正确的
$query = "select DISTINCT age from test where name = '$name' GROUP BY name";
$query = "select age from test where name = '$name' LIMIT 1";
<?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();