Monday 16 July 2018

Get Currently Selected MySQL Database with PHP

Get Currently Selected MySQL Database with PHP

When debugging a PHP script, or when your site contains multiple MySQL connections, it can be useful to know which database your PHP script is currently connected to.
In MySQL you can simply run the following query:
  1. SELECT DATABASE();  
Pretty easy right? We can do exactly the same thing in PHP by taking the above SQL query and extracting the result like so:

  1. $query = "SELECT DATABASE();";  
  2. $result = mysql_query($queryor die(mysql_error());  
  3. if ($row = mysql_fetch_assoc($result))  
  4. {  
  5.     print_r($row);  
  6. }  
Once the above has been ran it will then output something like so:
  1. Array  
  2. (  
  3.     [DATABASE()] => my_database  
  4. )  

0 comments:

Post a Comment