Friday 15 June 2012

php - Data fetched from mysql is displayed 2 times -



php - Data fetched from mysql is displayed 2 times -

i new php. want fetch particular info mysql , display in label.i have tried simple php coding.but displays fetched info 2 times(actually have created 2 columns such name , age in table called test).please help me.here coding:

displayform.php

<body> <form method="post" name="display" action="display.php" > come in name display info 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 test name = '$name'"; $result = mysql_query($query); while ($line = mysql_fetch_array($result)) { echo $line['age']; echo "<br>\n"; } ?>

the datas in table

name=janani age=25

the output displayed as

25 25

i have 2 rows bearing same name and/or age.

in order show 1 result, need is:

use either distinct group by, or limit 1.

i.e.:

$query = "select distinct age test name = '$name' grouping name";

or

$query = "select age test name = '$name' limit 1";

sidenote: suggest utilize mysqli prepared statements though, since code open sql injection.

<?php $db_host = "xxx"; // replace $db_name = "xxx"; // $db_user = "xxx"; // $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 test name = ? limit 1")){ // or 1 // if($statement=$conn->prepare("select distinct age test name = ? grouping 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();

php mysql sql

No comments:

Post a Comment