Page 1 of 1

DB displays "Resource id #3" instead of string, wh

Posted: Wed Jan 10, 2007 7:05 pm
by ykarmi
Hey guys, I wrote the following code to read from my db (the username and password in my file are different):

Code: Select all

<?php
$user="me";
$password="1234";
$database="testdb";
mysql_connect(localhost,$user,$password);
@mysql_select_db($database) or die( "Unable to select database");
$query="SELECT round1 FROM purchased WHERE user = 'test'";
$result=mysql_query($query);
echo "result: ".$result;
?>
The cell circled in red is the one that's supposed to be read (assuming that my code is correct)
Image
But instead of getting "result: yes", I end up getting "result: Resource id #3"
What does "Resource id #3" mean and Why does it appear instead of my actual value? Is my code wrong?
Thank you very much :D
Yuval Karmi

Posted: Wed Jan 10, 2007 7:11 pm
by volka
try

Code: Select all

<?php
$user="me";
$password="1234";
$database="testdb";
$mysql = mysql_connect('localhost',$user,$password) or die(mysql_error());
mysql_select_db($database, $mysql) or die(mysql_error());
$query="SELECT round1 FROM purchased WHERE user = 'test'";
$result=mysql_query($query, $mysql) or die(mysql_error().': '.$query);
// mysql_querry returns a result resource, fetch the actual records via mysql_fetch_array
$row = mysql_fetch_array($result, MYSQL_ASSOC);
if ( false===$row ) {
	echo 'no such record';
}
else {
	echo $row['round1'];
}
?>

Posted: Wed Jan 10, 2007 7:12 pm
by Ollie Saunders
hello again ykarmi. mysql_query() returns a result resource that can be converted to actual values with mysql_fetch_assoc(). Remember you only get sets of data from a db never individual values.

Thank you!

Posted: Wed Jan 10, 2007 7:42 pm
by ykarmi
Thank you soooo much to the both of you, you've been a great help!!! I'm still learning MY-SQL, and yes, I do use google, but the answers that I found didn't explain it as well as you did and I was confused. Thanks!!! :D :D :D

EDIT: in Volka's code, the MYSQL_ASSOC parameter is not needed for the mysql_fetch_array function. The diffult is MYSQL_BOTH and that works well. Just thought I'd mention! :D

Posted: Wed Jan 10, 2007 8:44 pm
by volka
Since my example only uses the associative index mysql_fetch_array is called with MYSQL_ASSOC. There's nothing wrong with that and I suggest to keep the parameter where it is.