Php mysql create database if not exists

匿名 (未验证) 提交于 2019-12-03 01:44:01

问题:

I want to create a database. Why is not the db created with this code?

$dbname = 'regulations_db';     $con = mysql_connect("localhost","root","pass");     if (!$con)     {         die('Could not connect: ' . mysql_error());     } if (mysql_num_rows(mysql_query("SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '". $dbname ."'"))) {         echo "Database $dbname already exists.";     }     else {         mysql_query("CREATE DATABASE '". $dbname ."'",$con);         echo "Database $dbname created.";     } 

This is working, but I think the first one is the best practice:

if (mysql_query("CREATE DATABASE IF NOT EXISTS regulations_db",$con))     {         echo "Database created";     }     else     {         echo "Error creating database: " . mysql_error();     } 

回答1:

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

As an example, check out the first answer here by another very smart StackOverflower.



回答2:

Three steps to fix this:

  1. Don’t specify the database name when connecting.
  2. Your SQL statement should be CREATE DATABASE IF NOT EXISTS php1.
  3. Call mysqli_select_db($link, 'php1') to make that the default database for your connection.


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!