Page 1 of 1
Retrieve a single data from MySQL
Posted: Fri Nov 20, 2009 11:37 am
by tehhparadox
Hi all
Here is my problem in a nutshell; I'm trying to connect to a mysql database and run a query that only gives one result, and get that data and bring it inside a variable in php.
Here is my code:
Code: Select all
$dbp = mysql_connect("localhost", "username", "password");
mysql_select_db("exampledb", $dbp);
$sql = "SELECT data FROM 'exampletable' WHERE id=1";
$data = mysql_query($sql, $dbp);
print $data;
This code does not give the value of the query result, but rather gives something strange. When I searched around, I found out that people used mysql_fetch_field() to get data. But as in my case, I'm only getting one value.. or maybe I'm totally wrong. Please could someone help me with this problem?
thanks
Re: Retrieve a single data from MySQL
Posted: Fri Nov 20, 2009 11:43 am
by pickle
mysql_fetch_assoc() or
mysql_fetch_array() should work for you.
mysql_fetch_field() just returns field information - but you want the data.
mysql_query() returns a result set that is a PHP resource. In order to extract the data out of it, you need to use one of those 2 functions. For example, if you use
mysql_fetch_assoc():
Code: Select all
$dbp = mysql_connect("localhost", "username", "password");
mysql_select_db("exampledb", $dbp);
$sql = "SELECT data FROM 'exampletable' WHERE id=1";
$result = mysql_query($sql, $dbp);
# added
$row = mysql_fetch_assoc($result);
$data = $row['data'];
print $data;
Re: Retrieve a single data from MySQL
Posted: Fri Nov 20, 2009 11:47 am
by tehhparadox
This will help me a lot. Thanks for the quick reply and thanks even more for the quality of info!
Re: Retrieve a single data from MySQL
Posted: Fri Nov 20, 2009 11:58 am
by tehhparadox
when I tested your code it gave the error:
Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\test.php on line 8
Why does xampp give this error?
Re: Retrieve a single data from MySQL
Posted: Mon Nov 23, 2009 9:57 am
by pickle
Check the online docs & see what situations have to occur for mysql_query to return a boolean (certainly FALSE).
Re: Retrieve a single data from MySQL
Posted: Wed Nov 25, 2009 3:46 pm
by abushahin
try this way with a while loop.
Code: Select all
<?php
$retrieveQuery = mysql_query("SELECT data FROM 'exampletable' WHERE id=1");
$num = mysql_num_rows($retrieveQuery);
if ($num > 0)
{
$i=0;
while ($i<$num) {
$data = mysql_result($retrieveQuery,$i,"data");
echo $data;
?>
<?php
$i++;
}
?>
<?php
}
else if ($num == 0)
{
?>
<p>
<?php echo "no data returned";?></p>
<?php
}
?>
hope that helps abu