我有一个来自Moodle的用户名数组,我想看到他们对应的id。因为它对$ array =('user1','user'2 ....)是不实际的,并且大小/内容可能会有所不同,我在这里找到了一个有用的功能,似乎可以做我需要的东西:
function apply_quotes($item)
{
return "'".mysql_real_escape_string($item)."'";
}
$dataClip=array_map("apply_quotes",$dataClip);
$allUsers=array_map("apply_quotes",$allUsers);
输出$ allUsers给我这个:
Array ( [0] => 'guest
' [1] => 'admin
' [2] => 'xpto.xy
' [3] => 'a.maia
' [4] => 'd.mano
' [5] => 'a.cabral
' [6] => 'd.mateus
' )
//$allUsers gets me all usernames of Moodle, $dataClip gets me all usernames from an url xml file.
$results=array_intersect((array)$dataClip,(array)$allUsers);
$ results的结果:
Array ( [0] => 'a.cabral
' [1] => 'a.maia
' [54] => 'd.mateus
' )
list($usernamewhere,$usernameparams)=$DB->get_in_or_equal($results,SQL_PARAMS_NAMED,'username');
$sql="SELECT u.id AS userid,u.username
FROM {user} u
WHERE u.username {$usernamewhere}";
$users=$DB->get_records_sql($sql,$usernameparams);
foreach($users as $user){
echo $user->userid. ' - ' . $user->username.'<br/>';
}
编辑:在查询之后,我没有输出。有解决方案吗?
答案 0 :(得分:2)
试试这个
$sql="SELECT u.id AS userid
FROM user u
WHERE u.username IN('".implode(',',$results)."')";
你错过了单引号。
不要在where子句
不要在mysql中使用{}
编辑:
更改此
$userids = $DB->get_records_sql($sql);
echo $userids;
到
$userids = $DB->get_recordset_sql($sql);
foreach ($userids as $ids) {
$userid = $ids->userid;
echo $userid;
}
答案 1 :(得分:1)
{}特定于Moodle,它将表名替换为完整的表名 - database + prefix。
http://docs.moodle.org/dev/Data_manipulation_API#moodle_database::get_records_sql.28.29
$ DB-&gt; get_records_sql()返回一个对象数组
对于原始问题,您收到语法错误,因为用户名未包含在引号中。
正确的方法是
$usernames = array('username1', 'username2', ... );
list($usernamewhere, $usernameparams) = $DB->get_in_or_equal($usernames, SQL_PARAMS_NAMED, 'username');
$sql = "SELECT u.id AS userid, u.username
FROM {user} u
WHERE u.username {$usernamewhere}";
$users = $DB->get_records_sql($sql, $usernameparams);
foreach ($users as $user) {
echo $user->userid . ' - ' . $user->username . '<br />';
}
答案 2 :(得分:0)
正确的是
$sql="SELECT u.id AS userid
FROM user u
WHERE u.username IN('".implode(',',$results)."')";
答案 3 :(得分:0)
SQL不接受语法。删除WHERE部分中的AS:
$sql="SELECT u.id AS userid
FROM {user} u
WHERE u.username IN(".implode(',',$results).")";