在INSERT TO中使用变量作为表名

时间:2012-12-21 02:31:31

标签: php mysql

你好我要在数据库中插入一些数据。 没有我的SQL错误,但数据没有插入数据库。我的代码是:

 mysql_query("SET CHARACTER SET 'utf8'");
  mysql_query("SET character_set_results=utf8");


if (isset($_POST['Submit'])){ 
$category= $_POST['category'];

if ($category==1) {$cat="rf_power";
$sub_cat=$_POST['power']; $dur="p_duration";}
if ($category==2) {$cat="rf_bts";
$sub_cat=$_POST['BTS']; $dur="b_duration";}
 if ($category==3) {$cat="rf_transmission";
 $sub_cat=$_POST['transmission']; $dur="t_duration";}
 if ($category==4) {$cat="core_network";$sub_cat=$_POST['core']; $dur="duration";}
 if ($category==5) {$cat="daisy_chain";
 $sub_cat=$_POST['daisy']; $dur="d_duration";}

 $dateid=date('Y-m-d');
 $s_name=mysql_real_escape_string($_POST['s_name']);
 $location=mysql_real_escape_string($_POST['city']);
 $alarm_type=mysql_real_escape_string($_POST['a_type']);
 $severity=mysql_real_escape_string($_POST['severity']);
 $reason=mysql_real_escape_string($_POST['reason']);
 $shift_operation=mysql_real_escape_string($_POST['shto_do']);
 $system_operation=mysql_real_escape_string($_POST['syto_do']);
 $start_time=mysql_real_escape_string($_POST['date1']);
 $end_time=mysql_real_escape_string($_POST['date2']);
 $dur=mysql_real_escape_string($_POST['date3']);
 echo $dateid;
 echo $s_name;
 echo $sub_cat;
 echo $location;
 echo $alarm_type;
 echo $severity;
 echo $start_time;
 echo $end_time;
 echo $dur;
 echo $reason;
 echo $shift_operation;
 echo $system_operation;
 echo $cat ;

  $sql = "INSERT INTO ".$cat." (dateid,system_name,sub_cat,location,alarmtype,severity,start_time,end_time,duartion,reason,shift_operation,system_operation)
    VALUES ('$dateid','$s_name','$sub_cat','$location','$alarm_type','$severity','$start_time','$end_time','$dur','$reason','$shift_operation','$system_operation')";
 }

所有通过回声打印正常。我认为错误是针对“INSERT INTO”。$ cat。“。$ cat就在这里?

1 个答案:

答案 0 :(得分:0)

从发布的代码中,您的查询似乎没有被执行,但存储在$sql内并坐在那里。从代码中没有任何实际执行查询,我在底部添加了这个。添加mysql_query($sql);将针对所选数据库运行脚本

 $sql = "INSERT INTO $cat (dateid,system_name,sub_cat,location,alarmtype,severity,start_time,end_time,duartion,reason,shift_operation,system_operation)
        VALUES ('$dateid','$s_name','$sub_cat','$location','$alarm_type','$severity','$start_time','$end_time','$dur','$reason','$shift_operation','$system_operation')";
    mysql_query($sql);