Click to See Complete Forum and Search --> : get error when fetch array


imname
February 29th, 2008, 04:31 AM
mysql_connect("localhost","root","");
$sql="SELECT tableA.ID,SUM(tableA.TotalAmount) FROM tableA,tableB WHERE tableB.ID=tableA.ID GROUP BY tableB.ID";
$sql_result=mysql_query($sql);

while($row=mysql_fetch_array($sql_result)){
echo "<BR>$row[1]<BR>";
}


When I run the code above, I get error ---> mysql_fetch_array(): supplied argument is not a valid MySQL result resource.

I also tried mysql_fetch_object and mysql_num_rows, but same error happen.

Thank you

PeejAvery
February 29th, 2008, 08:50 AM
This means that your query is not returning anything or is invalid. Check it by using a die() statement.

$sql_result=mysql_query($sql) or die(mysql_error());

Nibinaear
February 29th, 2008, 03:16 PM
You should check your sql separately to get this to work. Output the sql query using an echo statement and then paste it into your database program such as phpmyadmin or mysql query browser. Once you have the sql working, implement this and then try again.

If your sql doesn't work your query will return false and when you try and process your result variable you'll get an error- because no result variable is there. To handle this properly you might use a:



if($result=mysql_query($sql))
{
echo "do stuff";
}
else
{
echo "error";
}

imname
February 29th, 2008, 11:43 PM
I have tried to put the query in MySQL Query Browser,and the query returns results for tableA.ID,SUM(tableA.TotalAmount).

Nibinaear
March 1st, 2008, 11:45 AM
I have tried to put the query in MySQL Query Browser,and the query returns results for tableA.ID,SUM(tableA.TotalAmount).

Did you try your full query or just that section?

SELECT tableA.ID,SUM(tableA.TotalAmount) FROM tableA,tableB WHERE tableB.ID=tableA.ID GROUP BY tableB.ID

UPDATED

Also, check the following:

1) That your db connection is working by using an:


if(!mysql_connect("localhost","root",""))
{
echo "fails";
}
else
{
echo "works";
}


2) Are you using mysql_select_db("mydatabase"); ?