views:

104

answers:

3

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> 
+1  A: 

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

Col. Shrapnel
yep, i got Notice: SELECT username FROM users, i got table name users, and theres one user, why i keep getting this error?
sky
@sky can you paste exact error message here? Looks like some of it's text omitted. Can you look into page source for this?
Col. Shrapnel
Notice: SELECT username FROM users in /home/oiweiki1/public_html/yo2.us/error.php on line 14heres the error message
sky
@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());`
Col. Shrapnel
lol, thanks for the help, but it seem like same. ; p
sky
A: 

Check the error messages of MySQL using mysql_error:

<?php
$result = mysql_query('SELECT * FROM users');
$error = mysql_error();
if ($error != '')
    die($error);
?>
Cassy
die must die. as it break HTML and dirty practice at all
Col. Shrapnel
A: 

Usually I do the Mysql connecting like this:

$con = mysql_connect("host","user","passwd");
if (!$con)
{
   die('Could not connect: ' . mysql_error());
}
SpawnCxy
using die is very bad practice. at least 500 HTTP error must be sent on the production server instead of sensitive mysql information
Col. Shrapnel
@Shrapnel ,thanks for the note.
SpawnCxy