数据插入表mysql php并创建表动态错误?

时间:2013-12-19 06:10:41

标签: php mysql session

尝试动态创建数据库时出错。代码在下面分享。

<?php mysql_query("create table if not exists ".$month."(
            id int(11) primary key not null auto_increment,
            roll varchar(50) not null unique key )");

我的代码中是否有任何错误。需要帮忙。提前谢谢。

2 个答案:

答案 0 :(得分:1)

试试这个,

<?php mysql_query("create table if not exists '".$month."'(
        id int(11) primary key not null auto_increment,
        roll varchar(50) not null unique key )"); ?>

我已为$ month添加单引号

答案 1 :(得分:1)

请尝试使用此代码,

 $con = mysqli_connect("localhost", "user", "password", "database_name");
 // Check connection
 if (mysqli_connect_errno()) {
     echo "Failed to connect to MySQL: " . mysqli_connect_error();
 }

 $month = "jan";
 // Create table
 $sql = "CREATE TABLE IF NOT EXISTS " . $month . " (id int(11) primary key not null        auto_increment,roll varchar(50) not null unique key )";

 // Execute query
 if (mysqli_query($con, $sql)) {
     echo "Table " . $month . " created successfully";
 } else {
     echo "Error creating table: " . mysqli_error($con);
 }

OR

 $con = mysql_connect("localhost", "user", "password");
 if (!$con) {
     die('Could not connect: ' . mysql_error());
 }


 $db_selected = mysql_select_db("database_name", $con);

 if (!$db_selected) {
     die("Database not selected" . mysql_error());
 }
 $month = "feb";
 $sql = 'CREATE TABLE IF NOT EXISTS ' . $month . ' (id int(11) primary key not null auto_increment,roll varchar(50) not null unique key )';
 if (mysql_query($sql, $con)) {
     echo "Table " . $month . " created successfully";
 } else {
     echo "Error creating database: " . mysql_error();
 }