2012-02-06 115 views
-2

在我的PHP脚本我想在MySQL语句中使用的变量名作为表名,但是当我使用变量来为桌子命名它给我一个语法错误,如果没有使用`并且在使用'时说'不正确的表名''。代码附加以下为什么不能PHP变量被用作在MySQL INSERT语句中的表名

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(); 
} 

当我使用它回声相同的查询,如果我只是把TEST_TABLE直接在查询返回的变量$ tblName变量,而是一个与出查询变量正确执行。

+0

什么是实际的错误信息?另外,你可能想看看['mysql_select_db()'](http://php.net/manual/en/function.mysql-select-db.php) – Phil 2012-02-06 05:34:49

+0

$ tblName附近的错误消息变量是: 不正确的表名' – pmurph 2012-02-06 05:40:12

回答

1

你不使用mysql_select_db()。试试这个:

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(); 
} 

更换你的数据库名称eith dbname

+0

MySQL查询“使用\'test_schema \'”做什么mysql_select_db不 – pmurph 2012-02-06 05:42:42

0

我认为你是选择功能外数据库。这可能是因为可变的可访问性。

尝试把线内功能mysql_query("Use test_schema ");

function toQuery($tblName){ 
$t = "testtitle"; 
$art = "testarticle"; 
$auth = "testauthor"; 
mysql_query("Use `test_schema`"); 
return "INSERT INTO `$tblName` VALUES ('$t', '$art', '$auth', null)"; 
} 
+0

不要认为这是因为当我刚刚在INSERT把实际的表名(不变量)的问题声明,它的作品。 – pmurph 2012-02-06 13:11:33

相关问题