duanhong8839 2012-02-06 05:32
浏览 50

为什么不能将php变量用作mysql insert语句中的表名

In my PHP script I am trying to use variable name as the table name in a MySQL statement, but when I use the variable as the table name it give me a syntax error if no ` are used and says Incorrect Table Name '' when ` are used. The code is attached below

function toQuery($tblName){
   $t = "testtitle";
   $art = "testarticle";
   $auth = "testauthor";

       return "INSERT INTO `$tblName` VALUES ('$t', '$art', '$auth', null)";
}

mysql_connect("localhost","testuser","pass123");

mysql_query("Use `test_schema`");

if(mysql_query(toQuery("test_table"))){
    echo "Query: ".toQuery("test_table")." was run.";
}else{
    echo "Query: ".toQuery("test_table")." was not run. ".mysql_error();
}

When I use the variable $tblName variable it echos an identical query to if i just put test_table straight in the query returned, but the one with out the variable in query executes properly.

  • 写回答

2条回答 默认 最新

  • 普通网友 2012-02-06 05:41
    关注

    you don't use mysql_select_db() . try this :

    function toQuery($tblName){
       $t = "testtitle";
       $art = "testarticle";
       $auth = "testauthor";
    
           return "INSERT INTO `$tblName` VALUES ('$t', '$art', '$auth', null)";
    }
    
    mysql_connect("localhost","testuser","pass123");
    mysql_select_db('dbname');
    mysql_query("Use `test_schema`");
    
    if(mysql_query(toQuery("test_table"))){
        echo "Query: ".toQuery("test_table")." was run.";
    }else{
        echo "Query: ".toQuery("test_table")." was not run. ".mysql_error();
    }
    

    replace your database name eith dbname

    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!