抱歉,我不太擅长 PHP 和 SQL。我有一个用户名,它似乎可以正常工作,因为我可以回应它,这是正确的。如下所示。
echo 'Username: ' . $current_user->user_login . "\n";
echo 'User email: ' . $current_user->user_email . "\n";
echo 'User first name: ' . $current_user->user_firstname . "\n";
echo 'User last name: ' . $current_user->user_lastname . "\n";
echo 'User display name: ' . $current_user->display_name . "\n";
echo 'User ID: ' . $current_user->ID . "\n";
?>
这很好用。
我在一个类中有一个函数。我认为我可以传递一个 SQL 语句,其中用户名等于此变量,如下所示。然而,这似乎不起作用。
protected function _scandir($id) {
$files = array();
$sql = 'SELECT f.id, f.parent_id, f.name, f.size, f.mtime, f.mime, f.width, f.height, f.username, ch.id AS dirs
WHERE f.username = $username
FROM '.$this->tbf.' AS f
LEFT JOIN '.$this->tbf.' AS ch ON ch.parent_id=f.id
AND f.parent_id="'.$id.'"
GROUP BY f.id';
if ($res = $this->query($sql)) {
while ($r = $res->fetch_assoc()) {
$id = $r['id'];
$this->stat($id, false, $r);
$files[] = $id;
}
}
return $files;
}
我是不是漏掉了一些愚蠢或明显的东西。我只需要传递用户名变量并使用它来查询数据库。
这是原始查询 $
protected 函数 _scandir($id) { $文件=数组(); $sql = 'SELECT f.id, f.parent_id, f.name, f.size, f.mtime, f.mime, f.width, f.height, f.username, ch.id AS dirs 来自 '.$this->tbf.'当f 左连接 '.$this->tbf.' AS CH ON ch.parent_id=f.id WHERE f.parent_id="'.$id.'" AND f.username ="'.$username.'" 按 f.id 分组';
if ($res = $this->query($sql)) {
while ($r = $res->fetch_assoc()) {
$id = $r['id'];
$this->stat($id, false, $r);
$files[] = $id;
}
}
return $files;
}
最佳答案
您不能使用单引号将变量添加到字符串。除此之外,当你添加一个字符串进行查询时,你必须将它放入qoutes中。
除此之外,您的查询也是错误的。我
试试这个:
$sql = "
SELECT f.id, f.parent_id, f.name, f.size, f.mtime, f.mime, f.width, f.height, f.username, ch.id AS dirs
FROM ".$this->tbf." AS f
LEFT JOIN ".$this->tbf." AS ch ON (ch.parent_id=f.id AND f.parent_id=".$id.")
WHERE f.username = '".$username."'
GROUP BY f.id
";
假设 $username 和 f.username 是一个字符串, $id 和 f.parent_id 是整数
关于php sql 试图将用户名变量传递给 sql 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7313420/