detect if db table exists by php

Discussion in 'MySQL' started by gilgalbiblewheel, Mar 3, 2009.

  1. #1
    gilgalbiblewheel, Mar 3, 2009 IP
  2. w0tan

    w0tan Peon

    Messages:
    77
    Likes Received:
    6
    Best Answers:
    0
    Trophy Points:
    0
    #2
    A quick google search revealed a lot of results. Maybe you should have tried there first.

    Anyway, this bit of code looks to be the best.

    
    function table_exists ($table, $db) { 
    	$tables = mysql_list_tables ($db); 
    	while (list ($temp) = mysql_fetch_array ($tables)) {
    		if ($temp == $table) {
    			return TRUE;
    		}
    	}
    	return FALSE;
    }
    
    /** How to use it **/
    if (!table_exists("test_table", "my_database")) {
    	echo"No such table exists";
            //put your table creation code here
    }
    ?>
    
    Code (markup):
    Came from this page.

    I've modified the code a bit to fit your purposes.
     
    w0tan, Mar 3, 2009 IP
  3. gilgalbiblewheel

    gilgalbiblewheel Well-Known Member

    Messages:
    435
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    101
    #3
    Ok I got this:
    
    <?php 
    $db = "kjv";
    $table = "findings";
    /************************************************************************************************/
    function table_exists ($table, $db){ 
    	$tables = mysql_list_tables ($db); 
    	while (list ($temp) = mysql_fetch_array ($tables)){
    			if ($temp == $table){
    				return TRUE;
    			}
    		}
    	return FALSE;
    }
    
    /** How to use it **/
    if (!table_exists("test_table", "my_database")){
    	echo "No such table exists";
    	// Create table
    	mysql_select_db($db, $con);
    	$sql = "CREATE TABLE findings
    	(
    	ID MEDIUMINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    	book1 int,
    	chapter1 int,
    	verse1 int,
    	book2 int,
    	chapter2 int,
    	verse2 int,	
    	txtarea0 VARCHAR(60),
    	txtarea1 VARCHAR(60),
    	txtarea2 VARCHAR(60),
    	txtarea3 VARCHAR(60),
    	txtarea4 VARCHAR(60),
    	txtarea5 VARCHAR(60),
    	comments VARCHAR(60)
    	)";
    	
    	// Execute query
    	mysql_query($sql,$con);
    	//put your table creation code here
    }
    ?>
    PHP:
     
    gilgalbiblewheel, Mar 3, 2009 IP
  4. w0tan

    w0tan Peon

    Messages:
    77
    Likes Received:
    6
    Best Answers:
    0
    Trophy Points:
    0
    #4
    That message means that your not providing the right credentials when you connect to the database (I don't see any code to login in the code you posted). The rest of the errors are just a result of not being able to connect to the db. Look at the mysql_connect() functions on the w3cschools website for that info.
     
    w0tan, Mar 3, 2009 IP