Jump to content

[SOLVED] How to check if a database exists?


Pastulio

Recommended Posts

hey everybody,

 

I have a question that should be quite simple.

I'm writing a class to create Databases, and I'll also make one to create Tables.

 

But how do I check if a database already exists? just by checking if you can select it like so:

 

	// Select the MySQL database
	$this -> db_select = mysql_select_db ($this -> database);

		// Test the database selection
		if (!$this -> db_select) { return false; }

 

(don't mind the "$this" it's coded in OOP but I didn't think I would need to put it in the OOP forum for this simple example)

 

So is this the right way to check it or is there another way?

Link to comment
https://forums.phpfreaks.com/topic/57135-solved-how-to-check-if-a-database-exists/
Share on other sites

so I should do something like this?:

 


	$db_list = mysql_list_dbs($connection);

	while ($row = mysql_fetch_array($db_list)) {

		$database_List[] = $row['database'];
	    
	}

 

And then use a for loop to check the array contents row by row, or could it be done with one loop?

so I should do something like this?:

 


	$db_list = mysql_list_dbs($connection);

	while ($row = mysql_fetch_array($db_list)) {

		$database_List[] = $row['database'];
	    
	}

 

And then use a for loop to check the array contents row by row, or could it be done with one loop?

 

Yes but a for loop is not necessary, www.php.net/in_array  should work just fine.

I don't really know but it looked quite noob to me, because what if the database could not be selected because of another reason (of which I know absolutely nothing) it would just give a big error.

 

this is my final code:

 

<?php
function check_Existence () {

	$result = mysql_list_dbs ($this -> connection)

	while ($list = mysql_fetch_array($result)) {

		$database_list[] =  $list['database'];

	}

	if (in_array($this -> database, $database_list)) {

		return true;

	} else {

		return false;

	}

}
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.