swathi
swathi

Reputation: 107

retrieving a mysql query

I have written a mysql query and fetched the result as an assoc array using mysql_fetch_assoc().The query returns a list for two fields.I am looping through this field using through the result array and am extracting the value.how do i display the two fields since doing a plain echo is not working for me?The code which i have written is

Thanks in advance.

 $query = "SELECT x,y FROM table";
 $result = mysql_query( $query ,  $resourcelink);
 while( $s= mysql_fetch_assoc( $result ) )
 {
extract( $s );
    echo $x . " - " . $y . "<br />";
 }

Upvotes: 0

Views: 76

Answers (4)

VolkerK
VolkerK

Reputation: 96159

According to your SELECT statement mysql_fetch_assoc() returns an array like array('x'=>something, 'y'=>something)and extract() would "translate" that to $x='something' and $y='something', not $one and $two.

Try

error_reporting(E_ALL);
$query = "SELECT x,y FROM table";
$result = mysql_query( $query ,  $resourcelink) or die(mysql_error());
echo 'there are ', mysql_num_rows($result), " records in the result set\n";
while( false!==($row=mysql_fetch_array($result, MYSQL_ASSOC)) )  {
  echo $row['x'], ' ', $row['y'], "\n";
}

Upvotes: 0

knittl
knittl

Reputation: 265211

extract is a bad practice, furthermore your columns are probably called x and y and not one and two.

i suggest using the following:

echo htmlspecialchars($s['x']), ' - ', htmlspecialchars($s['y']);

Upvotes: 0

Roland Bouman
Roland Bouman

Reputation: 31961

I advise against using extract. it makes code very hard to follow.

I'd just do this:

$query = "SELECT x,y FROM table";
$result = mysql_query( $query ,  $resourcelink);
while( $s= mysql_fetch_assoc( $result ) ) {
    echo $s['x'], ' - ', $s['y'], '<br/>';
}

Upvotes: 1

Yacoby
Yacoby

Reputation: 55445

mysql_fetch_assoc returns an array of mappings of key to value. As you didn't retrieve one and two from the database, $one and $two ($s['one'] and $s['two'] respectively) don't exist. Therefore do something like this, using the columns you selected as keys.

 $query = "SELECT x,y FROM table";
 $result = mysql_query( $query ,  $resourcelink);
 while( $s= mysql_fetch_assoc( $result ) )
 {
    echo $s['x'] . " - " . $s['y'] . "<br />";
 }

Or if you want to continue using extract (I don't recommend it, it can lead to some hard to track down bugs)

 $query = "SELECT x,y FROM table";
 $result = mysql_query( $query ,  $resourcelink);
 while( $s= mysql_fetch_assoc( $result ) )
 {
    extract($s);
    echo $x . " - " . $y . "<br />";
 }

Upvotes: 0

Related Questions