SQL Query Function

PythonPython Forum LeaderThe Royal RAM
I tried to create a simple function which would do my sql queries for me but it doesnt seem to work...

Here it is:

[PHP]function mysql_query($sql)
{
$result = mysql_query($sql);
}

sql_query("SELECT * FROM `users`");

while($r=mysql_fetch_array($result)){
echo "$r[name]";
}[/PHP]

The error is:

Warning: mysql_fetch_array(): supplied arguement is not a valid MySQL result resource


Any ideas? Its probably just a simple problem im not picking up on.

Thanks

The Royal Ram

Comments

  • dabossdaboss WP V.I.P. ''The Boss'' Administrator
    are you sure 'name' is a field in your 'users' table?
  • PythonPython Forum Leader The Royal RAM
    yes...

    The Royal Ram

  • ChroderChroder Senior Member The Royal RAM
    You are forgetting about variable scope. $result only exists locally to the sql_query function, once the function ends, so does the $result.

    You can make it apply to the global scope:
    [php]$GLOBALS = mysql_query($sql);[/php]
    And it will be available outside of the function too. However, this is bad programming practice. If you don't want to worry about assign result sets, it's better to make a wrapper class. For example:
    [php]class Mysql
    {
    var $result;

    function query($sql)
    {
    $this->result = mysql_query($sql);
    }

    function fetch()
    {
    return mysql_fetch_array($this->result);
    }
    }

    $DB = new Mysql;

    $DB->query("SELECT * FROM `users`");

    while($r = $DB->fetch())
    {
    echo $r;
    }[/php]

    You'd obviously want more then those two methods, though. One for freeing results, num rows etc etc.
  • PythonPython Forum Leader The Royal RAM
    ahh ok cool. Thanks for that

    The Royal Ram

Sign In or Register to comment.