0

Possible Duplicate:
mysql_fetch_array() expects parameter 1 to be resource, boolean given in select

When i use the code below, im getting this error: Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource

when returning the data, anyone can fix it? Thanks!

<?php
$mysql_server_name="localhost"; 
$mysql_username=""; 
$mysql_password=""; 
$mysql_database=""; 

$conn=mysql_connect($mysql_server_name, $mysql_username,
                    $mysql_password);
?>

<?php 
$result = mysql_query("SELECT * FROM users"); 
$arrays = array(); 
while ($row = mysql_fetch_assoc($result)) { 
    foreach ($row as $key => $val) { 
        if (!array_contains_key($key)) { 
            $arrays[$key] = array(); 
        } 
        $arrays[$key][] = $val; 
    } 
} 
?> 
<script type="text/javascript"> 
<?php 
foreach ($arrays as $key => $val) { 
    print 'var ' . $key . ' = ' . json_encode($val) . ";\r\n"; 
} 
?> 
</script> 
Community
  • 1
  • 1
sky
  • 83
  • 7
  • Note that you should print the output of `mysql_error` only when developing (http://msdn.microsoft.com/en-us/library/ms995351.aspx#securityerrormessages_topic2). Other than that, the error should be logged where only the admins can read it, and some other error message should be displayed to users. As for `SELECT *`, read http://stackoverflow.com/questions/321299/what-is-the-reason-not-to-use-select. – outis Apr 19 '10 at 08:41
  • Good point @outis that's why `trigger_error` use is suggested – Your Common Sense Apr 19 '10 at 08:48

3 Answers3

1

this is not mysql_fetch_assoc problem but query problem
make it

$sql="SELECT * FROM users";
$result = mysql_query($sql) or trigger_error(mysql_error().$sql); 

and see actual error

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
  • yep, i got Notice: SELECT username FROM users, i got table name users, and theres one user, why i keep getting this error? – sky Apr 19 '10 at 08:57
  • @sky can you paste exact error message here? Looks like some of it's text omitted. Can you look into page source for this? – Your Common Sense Apr 19 '10 at 09:07
  • Notice: SELECT username FROM users in /home/oiweiki1/public_html/yo2.us/error.php on line 14 heres the error message – sky Apr 19 '10 at 09:09
  • @sky thats very strange. looks like an error occurred, but no error message. please try this, just another line below mysql_query: `echo htmlspecialchars(mysql_errno().mysql_error());` – Your Common Sense Apr 19 '10 at 09:59
  • lol, thanks for the help, but it seem like same. ; p – sky Apr 19 '10 at 12:15
0

Check the error messages of MySQL using mysql_error:

<?php
$result = mysql_query('SELECT * FROM users');
$error = mysql_error();
if ($error != '')
    die($error);
?>
Dan Soap
  • 10,114
  • 1
  • 40
  • 49
0

Usually I do the Mysql connecting like this:

$con = mysql_connect("host","user","passwd");
if (!$con)
{
   die('Could not connect: ' . mysql_error());
}
Young
  • 7,986
  • 7
  • 43
  • 64