Checking if a database exists

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

Checking if a database exists

Post by Luke »

How would you check if a mysql database exists with php?
User avatar
raghavan20
DevNet Resident
Posts: 1451
Joined: Sat Jun 11, 2005 6:57 am
Location: London, UK
Contact:

Post by raghavan20 »

I wrote this function a few days ago...I am have cut this out of a class...

Code: Select all

/*
	* Find whether there a database exists under the name provided
	* Input - databaseName: String
	* Return: Boolean
	*/
	function isDatabase($databaseName){
		$valid = FALSE;
		if (empty($databaseName) === FALSE){
			$query = "show databases";
			if (is_resource($result = mysql_query($query)) === TRUE){
				if (mysql_num_rows($result) > 0){
					while ($row = mysql_fetch_row($result)){
						if ($row[0] == $databaseName){
							$valid = TRUE;
						}
					}
				}
			}
		}
		//DEBUG//echo "<br />DEBUG: isDatabase() - is database valid: ".$valid;
		return $valid;
	}
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: Checking if a database exists

Post by John Cartwright »

The Ninja Space Goat wrote:How would you check if a mysql database exists with php?
with php? Makes much more sense to use MYSQL to do the checking :wink:
Post Reply