为什么可以';t php变量不能用作mysql insert语句中的表名

为什么可以';t php变量不能用作mysql insert语句中的表名,php,mysql,Php,Mysql,在我的PHP脚本中,我试图在MySQL语句中使用变量名作为表名,但是当我使用变量作为表名时,如果没有使用`则会出现语法错误,如果使用`则会显示不正确的表名'。代码附在下面 function toQuery($tblName){ $t = "testtitle"; $art = "testarticle"; $auth = "testauthor"; return "INSERT INTO `$tblName` VALUES ('$t', '$art', '$au

在我的PHP脚本中,我试图在MySQL语句中使用变量名作为表名,但是当我使用变量作为表名时,如果没有使用`则会出现语法错误,如果使用`则会显示不正确的表名'。代码附在下面

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

当我使用变量$tblName变量时,如果我只是将test\u表直接放入返回的查询中,它会回显一个相同的查询,但是查询中没有变量的查询会正确执行。

您不使用mysql\u select\u 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();
}

将数据库名称替换为
dbname

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

尝试放置行
mysql\u查询(“使用
test\u模式
内部函数

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

实际的错误信息是什么?另外,您可能希望查看关于$tblName变量的错误消息:不正确的表名“mysql查询”使用'test\u schema`“执行mysql\u select\u db所做的操作。我不认为这是问题所在,因为当我将实际表名(而不是变量)放在INSERT语句中时,它可以工作。