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
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?

Link to comment
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?

 

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

Link to comment
Share on other sites

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;

	}

}
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.