在我的PHP脚本中,我试图在MySQL语句中使用变量名作为表名,但当我使用变量作为表名时,如果不使用`are,它会给我一个语法错误,而当使用`are时,它会说"表名不正确"。代码附在下方
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_table,但查询中没有变量的查询执行正常,它会返回一个相同的查询。
您不使用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();
}
将数据库名称替换为dbname
我认为您选择的是函数之外的数据库。这可能是因为可变的可访问性。
尝试将行mysql_query("Use
testrongchema ");
放入函数中。
function toQuery($tblName){
$t = "testtitle";
$art = "testarticle";
$auth = "testauthor";
mysql_query("Use `test_schema`");
return "INSERT INTO `$tblName` VALUES ('$t', '$art', '$auth', null)";
}