Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/66.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
MySQL查询函数似乎阻止在表名中使用PHP变量_Php_Mysql_Sql_Function_Variables - Fatal编程技术网

MySQL查询函数似乎阻止在表名中使用PHP变量

MySQL查询函数似乎阻止在表名中使用PHP变量,php,mysql,sql,function,variables,Php,Mysql,Sql,Function,Variables,我有一个自定义的query()函数,如下所示: $link = mysqli_connect("localhost","username","password"); mysqli_select_db($link, "database_table"); //executes a given sql query with the params and returns an array as result function query() { global $link; $debug = false

我有一个自定义的
query()
函数,如下所示:

$link = mysqli_connect("localhost","username","password");
mysqli_select_db($link, "database_table");

//executes a given sql query with the params and returns an array as result
function query() {
global $link;
$debug = false;

//get the sql query
$args = func_get_args();
$sql = array_shift($args);

//secure the input
for ($i=0;$i<count($args);$i++) {
    $args[$i] = urldecode($args[$i]);
    $args[$i] = mysqli_real_escape_string($link, $args[$i]);
}

//build the final query
$sql = vsprintf($sql, $args);

if ($debug) print $sql;

//execute and fetch the results
$result = mysqli_query($link, $sql);
if (mysqli_errno($link)==0 && $result) {

        $rows = array();

        if ($result!==true)
        while ($d = mysqli_fetch_assoc($result)) {
            array_push($rows,$d);
        }

        //return json
        return array('result'=>$rows);

} else {

    //error
        return array('error'=>'Database error');
}
}
传递给上述活动函数的变量有:

$pass=$\u GET['password']
$user=$\u获取[用户名]
$userTable=“myTable\u name”

导致问题的唯一变量是
$userTable=“myTable\u name”
如果我将名称直接放入
query()
函数,如下所示:

$result = query("INSERT INTO myTable_name(username, password) VALUES('%s','%s')", $user, $pass);

那就没问题了。但出于其他原因,我需要能够将其作为PHP变量。我尝试了
“$userTable.”
“$userTable”
,并列举了一些例子。我的猜测是,我需要调整
query()
函数,以某种方式包含变量,就像我对
$pass
$user
所做的那样。是这样吗?如果是这样的话,最干净的方法是什么?谢谢

好的,所以我知道有一个简单的解决方案。我发现问题与变量的定义位置有关。我必须在函数中移动变量定义。该变量随后被提取出来,现在运行正常

此查询语法最终解决了以下问题:

$login=query(“从$userTable中选择用户名,其中用户名='%s'限制1',$user”)


感谢所有发表评论的人提供的帮助。

与其将查询字符串放入
query()
,不如先将其保存到变量中。然后你可以回显查询字符串,看看你是否得到了你想要的。到底是什么不起作用?mysql_error()的输出是什么?您是否尝试过将table name变量包装为tildas,例如,
$userTable
我认为Dave的意思是backticks(``),而不是tildas(~),我尝试过backticks。。。也不行。输出为
{“error”:“注册失败”}
@JonathanKuhn您能提供一个代码片段或链接来帮助我更好地理解您的解决方案吗?
$result = query("INSERT INTO myTable_name(username, password) VALUES('%s','%s')", $user, $pass);