Detecting/creating MySQL database
Why this code does not recognize the existing database?
$result = mysql_query("SHOW DATABASES LIKE $database", $conn);
echo $result." aaaaaaaaaaaaaaaaaaa<br>";
if ($result)
{
echo ("Datebase <font color='#FF0000'><b> $database </b></font> already exist.<br /><br />");
}
else
{
mysql_query("create database IF NOT EXISTS $database CHARACTER SET utf8 COLLATE utf8_general_ci");
echo ("Datebase <font color='#FF0000'><b> $database &开发者_Python百科lt;/b></font> is succesfully created.<br /><br />");
}
This code make my somekinda sick...
Here is a good code:
<?php
$query = "SHOW DATABASES LIKE ". $database;
$mysqlquery = mysql_query($query);
if($mysqlquery){
echo '<b>Database already exist.<br>';
}
else
{
$createquery = "CREATE DATABASE IF NOT EXISTS ". $database ." CHARACTER SET utf8 COLLATE utf8_general_ci";
$mysqlcreatequery = mysql_query($createquery);
if($mysqlcreatequery){
echo 'Database '. $database .' created. ';
}
else
{
echo 'Database is not created!';
}
}
?>
You forgot the quotes (always necessary when using strings in SQL) :
$result = mysql_query("SHOW DATABASES LIKE '$database'", $conn);
As the pattern is a string, you'll have to quote it:
"SHOW DATABASES LIKE '$database'"
The database is a string as stated by Dr.Molle. Also, watch out for wildcards. An _
is a single character wildcard, so when you look for the database order_2010
it will also match orders2010
, which will lead to the assumption that order_2010
is indeed an existing database.
Small chance, but I thought I should mention it. :)
精彩评论