且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

PHP MySQL创建数据库(如果不存在)

更新时间:2022-12-05 22:35:18

只需做一个简单的mysql_select_db(),如果结果为假,则继续进行创建.

Just do a simple mysql_select_db() and if the result is false then proceed with the creation.

例如,请查看另一个非常聪明的***er的第一个答案.

<?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);
?>