Nibiru Nibiru
Nibiru Nibiru

Reputation: 67

PHP: Is it possible to execute a MySQL statement to create a DATABASE even though I am already connected to my database?

I've been wondering if it's possible to create a new database using mysqli_query() even though I'm already connected to my database?

$create_new_db = mysqli_query($user_conn, "CREATE DATABASE sample_db");

if($create_new_db) {
echo 'new database has been created';
} else {
echo 'Error while creating new database.';
}

my variable $user_conn has a database connection named db_maindb. So is it still possible to create a new database when I'm connected to my db_maindb database?

Upvotes: 1

Views: 49

Answers (1)

ScaisEdge
ScaisEdge

Reputation: 133360

Like you have in you code ..

assuming you can connect to an existing database and your connected user has grant for create database you can

<?php
$servername = "localhost";
$username = "username";
$password = "password";

// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

// Create database
$sql = "CREATE DATABASE sample_db";
if ($conn->query($sql) === TRUE) {
    echo "Database created successfully";
} else {
    echo "Error creating database: " . $conn->error;
}

$conn->close();
?>

Upvotes: 3

Related Questions