user1903898
user1903898

Reputation: 75

Retrieve MySQL field using PHP

I need to get a field from a mySQL database using PHP The problem is that in my mysql panel I use this sql code:

SELECT * FROM TESTS WHERE TEST_ID=1

and I get exactly what I want (I see the row that I want to display) But if i use this code in PHP:

<?php
$con=mysql_connect("localhost", "root", "psw")  or die("\nConnection Failed\n");

mysql_select_db("mydb")or die("\nDB Failed\n");

$query = "SELECT * FROM TESTS WHERE TEST_ID=1";
$result=mysql_query($query);

echo $result;
mysql_close($con);
?>

all I get is "Resource ID #3"

why??

Upvotes: 0

Views: 82

Answers (5)

Yogesh Pingle
Yogesh Pingle

Reputation: 3665

Try to fetch result in any variable and print that It will work.
Like this :

<?php
$con=mysql_connect("localhost", "root", "psw")  or die("\nConnection Failed\n");

mysql_select_db("mydb")or die("\nDB Failed\n");

$query = "SELECT * FROM TESTS WHERE TEST_ID=1";
$result=mysql_query($query);

$row = mysql_fetch_array($result)
print_r($row);

mysql_close($con);
?>

Hope this will help you... :)

Upvotes: 0

bencoder
bencoder

Reputation: 846

the $result is a resource which is a link to a result set from mysql. To get the actual data you have to do something like:

$data = mysql_fetch_assoc($result);
print_r($data);

You would need to repeat the mysql_fetch_assoc() call for each row you want to retrieve, until it returns false, indicating there are no more rows, which can be done in a while loop like this:

while ($data = mysql_fetch_assoc($result)) {
    print_r($data);
}

Upvotes: 3

Epoc
Epoc

Reputation: 7496

Watch out :

This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used.

Upvotes: 3

Martin
Martin

Reputation: 1508

You have received a MySQL resource instead of the resultset you want. You've only received a pointer to the result.

You have to use functions like mysql_fetch_object, mysql_fetch_assoc, mysql_fetch_row etc to get the wanted resultset. Please check the manual here:

http://php.net/manual/en/book.mysql.php

Upvotes: 1

John Woo
John Woo

Reputation: 263803

you can use mysql_fetch_assoc

$result=mysql_query($query);
while ($row = mysql_fetch_assoc($result)) 
{
    echo $row["userid"]; // sample column
    echo $row["fullname"];
    echo $row["userstatus"];
}

Upvotes: 1

Related Questions