php - 为什么我的 Moodle 查询在 "Ad hoc database queries"中有效,但在我的插件中却无效?

标签 php mysql moodle

我有以下查询来检索自定义 Moodle 插件中的学术顾问。

学术顾问角色配置如下:https://docs.moodle.org/en/Parent_role

我已经在 Ad hoc 数据库查询(以及 MySQL Workbench)中运行了它,它在这两种情况下都运行良好,但由于某些奇怪的原因,它在我的插件中不起作用。

db_update.php :

function get_academic_advisees($userid) {
    global $DB;

    $sql = 'SELECT child.username, child.firstname, child.lastname
            FROM {user} user
            JOIN {role_assignments} ra ON ra.userid = user.id
            JOIN {role} role ON role.id = ra.roleid
            JOIN {context} ctx ON ctx.id = ra.contextid 
            AND ctx.contextlevel = 30
            JOIN {user} child ON child.id = ctx.instanceid
            WHERE role.shortname = "academic_adviser"
            and user.username = ?';

    return $DB->get_records_sql($sql, array($userid));
}

在我的attendance_form.php页,包含在 attendance.php 中(调用 db_update.php ):

require_once("{$CFG->libdir}/formslib.php");

class attendance_form extends moodleform {

    function definition() {
        $mform =& $this->_form;

        $mform->addElement('html', '<h2>' . get_string('attendance', 'local_attendance')  . '</h2>');
        $mform->addElement('html', '<p>This report allows you to retrieve attendance data for your academic advisees.</p>');

        //$mform->addElement('text', 'student_number', get_string('student_number', 'local_attendance'));
        global $USER;
        $userid = $USER->id;
        $myAdvisees = array();
        $adviseeArray = array();
        $myAdvisees = get_academic_advisees($userid);
        foreach($myAdvisees as $myAdvisee) {
            $key = $myAdvisee->username;
            $value = $myAdvisee->firstname . $myAdvisee->lastname . '(' . $myAdvisee->username . ')';
            $adviseeArray[$key] = $value;
        }

        $mform->addElement('select', 'student_number', get_string('student_number', 'local_attendance'), $adviseeArray);

        $this->add_action_buttons(true, get_string('save', 'local_attendance'));
    }
}

最佳答案

该函数采用参数“userid”,但在查询中它会尝试将其与“user.username”相匹配。

所以,你需要输入:

$userid = $USER->username;

如果你想让它在你的表单中工作。

此外,请从 $mform =& $this->_form 中删除 & - Moodle 很久以前就停止支持 PHP 4!

关于php - 为什么我的 Moodle 查询在 "Ad hoc database queries"中有效,但在我的插件中却无效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46585981/

相关文章:

web-services - 使用 Web 服务获取 Moodle 中的所有用户

php - 强制下载YouTube视频

javascript - POST 请求适用于 Postman,但不适用于 axios 或 .fetch()

javascript - 如果页面上的窗口打开并且用户关闭窗口,则重新加载当前窗口?

mysql - 加入多个问题

mysql - 同时为许多表创建列并从表名填充它_MYSQL

moodle - 如何就地编辑上传到 Moodle 的文件?

php - 在 SQL 语句中,如果没有找到特定查询的任何内容,则返回一个条目

php - 下拉菜单选择未发送到数据库?改为插入空值

php - AJAX/PHP 自动显示更新值