Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    Regular Coder
    Join Date
    Sep 2007
    Location
    AZ, USA
    Posts
    685
    Thanks
    6
    Thanked 46 Times in 46 Posts

    PHP global var and mysql_list_tables()

    I'm trying to make a function to check if a certain table exists in the database, and this line is giving me trouble:
    Code:
      $tables = mysql_list_tables($db);
      $num_tables = mysql_numrows($tables);
    When I manually hard-code a database name instead of putting the global var $db, it works. What am I doing wrong? I know for a fact that $db is accessible by the function and that it is the correct database name. If it matters, $db was declared inside another function as global $db. The error is this:
    Code:
    Warning: mysql_numrows(): supplied argument is not a valid MySQL result resource in /home/nathan/public_html/testzone/database/testnewphp.php on line 16
    Table does not exist.
    Line 16 is the second line in the function,
    Code:
     $num_tables = mysql_numrows($tables);
    If it matters, the complete code for the function is this:
    Code:
    function table($table)
    {
      $tables = mysql_list_tables($db);
      $num_tables = mysql_numrows($tables);
      $i = 0;
      $exist = 0;
      while($i < $num_tables) {
        $tablename = mysql_tablename($tables, $i);
        if ($tablename==$table) $exist=1;
        $i++;
      }
      if ($exist==0){
        die("Table does not exist.");
      } else {
        $from=$table;
      }
    }

  • #2
    teh Moderatorinator
    Join Date
    Sep 2004
    Location
    USA
    Posts
    2,472
    Thanks
    4
    Thanked 40 Times in 40 Posts
    That seems like a lot of work to check for a table - I would take a different approach and run a mysql query and then do a num_rows on that like:
    SHOW TABLES LIKE tablename

    Wrap that in a mysql_query + mysql_num_rows.

    Good luck;

  • #3
    Regular Coder
    Join Date
    Sep 2007
    Location
    AZ, USA
    Posts
    685
    Thanks
    6
    Thanked 46 Times in 46 Posts
    Thanks, that's a good solution and works better.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •