Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a database if it doesn't exist, using PHP?

Tags:

php

mysql

How do I create a database if it doesn't exist, using PHP?

like image 461
Awais Avatar asked Jun 28 '10 09:06

Awais


People also ask

How create database if not exists in PHP?

php $db = new mysqli("localhost","root",""); $create_db = "CREATE DATABASE IF NOT EXISTS ifsclist"; if($db->connect_error) { die("connection error"); } $response = $db->query($create_db); if($response) { echo "When created or Already exists"; } else{ echo "Something wrong!"; } ?>

How do you create a database that does not exist?

We can create a new database in MySQL by using the CREATE DATABASE statement with the below syntax: CREATE DATABASE [IF NOT EXISTS] database_name. [CHARACTER SET charset_name] [COLLATE collation_name];

Can you use PHP without a database?

Features. Login without using the database. Username and Password stored in PHP array. The ideal process to protect small pages.

Which clause is used to create a database only if it doesn't already exist?

6. To create a database only if it doesn't already exist, which clause is used? Explanation: The 'CREATE DATABASE' statement supports many optional values. To create a database named 'my_db' only if it doesn't already exist, we write 'CREATE DATABASE IF NOT EXISTS my_db'.


2 Answers

Presuming you're talking about a MySQL database - you want to use mysql_query and mysql_select_db.

Note that mysql_create_db is deprecated.

<?php
// Connect to MySQL
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}

// Make my_db the current database
$db_selected = mysql_select_db('my_db', $link);

if (!$db_selected) {
  // If we couldn't, then it either doesn't exist, or we can't see it.
  $sql = 'CREATE DATABASE my_db';

  if (mysql_query($sql, $link)) {
      echo "Database my_db created successfully\n";
  } else {
      echo 'Error creating database: ' . mysql_error() . "\n";
  }
}

mysql_close($link);
?>
like image 178
Dominic Rodger Avatar answered Sep 20 '22 13:09

Dominic Rodger


Since you mention WAMP I'll assume you're talking about MySQL.

It can be tricky. Assuming that your PHP script runs with all the required credentials (which is by itself a questionable idea), you can run this query:

SHOW DATABASES

If the DB does not show up there, you can assume it doesn't exist and create it with one of these queries:

CREATE DATABASE foo ....

or:

CREATE DATABASE IF NOT EXISTS foo ...

Right after that, you need to check the return value for whatever PHP function you are using (e.g. mysql_query). The above queries will fail if your user is now allowed to see all the existing databases or it's not allowed to create new databases.

In general, I find the whole concept kind of scary. Handle it with care! ;-)

like image 33
Álvaro González Avatar answered Sep 21 '22 13:09

Álvaro González