Selecting an Existing Database in PHP

Q

How To Select an Exiting Database in PHP?

✍: FYIcenter.com

A

The first thing after you have created a connection object to the MySQL server is to select the database where your tables are locate, by using the mysql_select_db() function. If your MySQL server is offered by your Web hosting company, they will assign a database to you and provide you the database name. You should use this name to select your database as your current database. The following script shows you how to select a database called "fyi". It also shows you how to put all the database connection statements in a single include file, and re-use it in all of your PHP pages.

Create the include file, connect.php, with the following statements:

<?php
  $server = "localhost";
  $username = "";
  $password = "";
  $database = "fyi";
  $con = mysql_connect($server, $username, $password);
  mysql_select_db($database);
?>

To test this database connection and selection include file, try the following script:

<?php
  include "mysql_connection.php";

  $sql = 'SHOW TABLES';
  if ($rs = mysql_query($sql, $con)) {
    print(mysql_num_rows($rs) . " tables in the database.\n");
  } else {
    print("SHOW TABLES failed.\n");
  }

  mysql_close($con); 
?>

You will get something like this:

0 tables in the database.

 

Running a SQL Statement in PHP

Creating a Database in PHP

Working with MySQL Database in PHP

⇑⇑ PHP Tutorials

2016-10-20, 2181🔥, 0💬