PHP MySQL tutorial

Selecting Mysql Database via PHP Script

Before creating any tables in the database or performing any operation on the database of your choice, you first have to switch to that database. By switching to database means selecting a database so that all future queries are executed on that particular database. To select a database, you need to execute following query.

Use dbname;

It is noticeable that we have appended a semi-colon after the query. It is optional to do so, but if you plan to execute multiple queries in a single go, do end your query with a semi colon.

Selecting Database via Object Oriented MySQLi

To select a database via PHP is simple. Pass the query for selecting database to the query function of the mysqli object and rest of the task will be done by PHP. The following example demonstrates this concept.



Using MySQLi for selecting Database



connect_error) {
    die("Connection not established: " . $connection->connect_error);
} 
    
// Selecting Database
$query = "Use Hospital";
if ($connection->query($query) === TRUE) {
    echo "database selection successful";
} else {
    echo "Unable to select database " . $connection->error;
}

$connection->close();
?>
     


Download the code

The above code will select database named ‘Hospital’ from the server. Remember that you need to have Hospital database created on your before you select it.

Select Database via Procedural MySQLi

For procedural MySQLi database selection is very simple. Just replace mysqli object with mysqli_connect function. Have a look at second example.




Using MySQLi for Database Selection 



connect_error) {
    die("Connection not established: " . $connection->connect_error);
} 
    
// Selecting Database
$query = "USE Hospital";
if ($connection->query($query) === TRUE) {
    echo "Database selection successful.";
} else {
    echo "Unable to select database " . $connection->error;
}

$connection->close();
?>
    



Download the code

<<< Drop Database in MySQL via PHP ScriptCreate Table in MySQL via PHP Script >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .