1

I am using wamp server 3.0.6, mysql 5.7.14 and php 5.6.25. I am new to php. I need a function which can check if database is exist. if not create one. if database exist execute some code.

$dbname = "mydb";
if($dbname exist){
   // do someting
} else {
   // create new database.
   database name = $dbname;
}

I know SQL command CREATE DATABASE IF NOT EXISTS mydb. But I don't want to use this and it doesn't work on my application.

7
  • Why doesn't it work for your application? Commented Dec 25, 2016 at 12:29
  • As I said I am new to php and mysql. I don't know how to use squl command to get my work done with php. Commented Dec 25, 2016 at 12:42
  • Are you going to gave a different database from which you can fire SQL and check some other database? Commented Dec 25, 2016 at 12:50
  • no. Not like this. Commented Dec 25, 2016 at 12:56
  • So you want to check if the database you are going to connect exists or not? Commented Dec 25, 2016 at 13:00

1 Answer 1

1

Try the following MySQL query:

SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = 'mydb'

And in php something like:

<?php

    $connection;
    $dbname = 'mydb'
    $username = 'username';
    $password = "password";

    $connection = new PDO("mysql:host=localhost", $username, $password);
    $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 

    $stmt = connection->prepare("SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME =:dbname");
    $stmt->execute(array(":dbname"=>$dbname));
    $row=$stmt->fetch(PDO::FETCH_ASSOC);

    if($stmt->rowCount() == 1)
    {
        echo 'db exists';
        // or do other stuff    
    }
    else { echo 'db does not exist'; }
?>
Sign up to request clarification or add additional context in comments.

5 Comments

thanks for the answer. can u give me a function how to use this MySQL command in php?
I don't use PDO. I use mysqli.
@Kurt OP doesn't know if the database exists or not let alone fire your SQL
Indeed, changed it.
I don't know how to change it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.