Moodle enrol_manual_enrol_users api error - php

I have been getting the error below when i try to enroll users to moodle through enrol_manual_enrol_users
Array ( [exception] => invalid_parameter_exception [errorcode] => invalidparameter [message] => Invalid parameter value detected [debuginfo] => enrolments => Invalid parameter value detected: Missing required key in single structure: roleid )
This is my code
$MoodleRest = new MoodleRest('http://localhost/moodle/webservice/rest/server.php', $this->token);
$enrolment = array(
"userid" => $user_id,
"courseid" => $course_id,
"roleid" => 4
);
$enrolments = array(array($enrolment));
$params = array( 'enrolments' => $enrolments );
$result_query = $MoodleRest->request('enrol_manual_enrol_users', $params);
if (!empty($result_query['exception'])) {
print_r(array('Error querying enroll', $result_query));
die();
}

$MoodleRest = new MoodleRest('http://40.81.1.212/moodle/webservice/rest/server.php', $this->token);
$par = array( //e_s_s
'enrolments' => array( //e_m_s
array( //e_s_s
'userid' =>$user_id ,
'courseid' =>$course_id , // PARAM_NUMBER VALUE_REQUIRED[]
'roleid' =>$role_id //PARAM_RAW VALUE_OPTIONAL [] ))
);
print_r($par);
echo "<br><br>";
$result_query = $MoodleRest->request('enrol_manual_enrol_users', $par);
if (!empty($result_query['exception'])) {
print_r(array('Error querying enroll', $result_query));
//die();
}
var_dump($result_query);
echo '</br>************************** Server Response EnrollUser()**************************</br></br>';

Related

Get `Warning: mysqli_real_escape_string()` after update database

I try to make my custom code to update data to my custom database table
after I send the data I get:
Warning: mysqli_real_escape_string() expects parameter 2 to be string,
array given in .../wp-includes/wp-db.php on line 1156
My table structure is:
table name: wp_wlm_user_options
column names: ID, user_id, option_name, option_value
My code is:
if (isset($_POST['submit'])) {
$user_id = $_POST['user_id'];
$table = 'wp_wlm_user_options';
$meta = array();
foreach ($wlm_user_info as $key => $value) {
$get_meta = $value['option_name'];
array_push($meta, $get_meta);
}
//var_dump($meta);
$value = array(
'custom_firstname' => $_POST['first_name'],
'custom_lastname' => $_POST['last_name'],
'custom_text_dateofbirth' => $_POST['text_dateofbirth'],
'custom_radio_gender' => $_POST['radio_gender'],
'custom_landlinephone' => $_POST['landlinephone'],
'custom_GoogleHangoutsId' => $_POST['GoogleHangoutsId']
);
$format = array(
'%s',
'%s'
);
//print_r($meta,$value);
$data = array(
'user_id' => $user_id,
'option_name' => $meta,
'option_value' => maybe_serialize($value)
);
$format = array('%d','%s','%s');
$where = array(
'user_id' => $user_id,
'option_name' => $meta
);
$x = $wpdb->update($table, $data, $where, $format);
//$x = $wpdb->update($table, $data, $where);
if($x){
echo '<h1>data has been save</h1>' ;
}
Can anyone tell me what is wrong with this?
Due to your poor information we can only guess.
You might want something like this:
if (isset($_POST['submit']))
{
$user_id = $_POST['user_id'];
$table = 'wp_wlm_user_options';
$values = array(
'custom_firstname' => $_POST['first_name' ],
'custom_lastname' => $_POST['last_name' ],
'custom_text_dateofbirth' => $_POST['text_dateofbirth'],
'custom_radio_gender' => $_POST['radio_gender' ],
'custom_landlinephone' => $_POST['landlinephone' ],
'custom_GoogleHangoutsId' => $_POST['GoogleHangoutsId']
);
$format = array('%s');
$whereformat = array('%d','%s');
foreach($values as $key => $val)
{
$data = array(
'option_value' => maybe_serialize($val)
);
$where = array(
'user_id' => $user_id,
'option_name' => $key
);
$num_rows = $wpdb->update($table, $data, $where, $format, $whereformat);
if($num_rows !== false){
echo "<h1>$key has been saved</h1>" ;
}
}
};
The code above does multiple updates mapping the data to option_name and option_value for each update() invocation. You don't need to update fields of the WHERE clause with unchanged values.
You can find the official documentation on wordpress.org

Saving PHP variable to MySQL INT is always 0

I am having a problem passing a variable to be saved as INT in MySQL. The closest thing I could find to my issue is this question but I have already verified that I am not using single and double quotes. When I print_r($this->session->userdata('subdomain')) I see the correct subdomain id on my screen (in this case 10), but when I try passing this using $params it always save subdomain_id as 0 and I can not figure out why.
Here is Project_assignees_model:
function add_prefix_project_assignees($params)
{
$this->db->insert('prefix_project_assignees',$params);
return $this->db->insert_id();
}
Here is my Project controller (Specifically it is the $assignees array):
function edit($entry_id)
{
$this->load->library('form_validation');
$this->form_validation->set_rules('client_id','Client Id','required|integer');
$this->form_validation->set_rules('title','Project Title','required|max_length[255]');
$this->form_validation->set_rules('project_status','Project Status','required');
$this->form_validation->set_rules('project_details','Project Details','required');
$this->form_validation->set_rules('project_estimated_hours','Project Estimated Hours','required|max_length[255]');
$this->form_validation->set_rules('end','Project Deadline','required');
if($this->form_validation->run())
{
date_default_timezone_set("America/New_York");
$date = date("Y-m-d h:i:sa");
$params = array(
'subdomain_id' => $this->session->userdata('subdomain'),
'client_id' => $this->input->post('client_id'),
'title' => $this->input->post('title'),
'project_status' => $this->input->post('project_status'),
'project_details' => $this->input->post('project_details'),
'project_last_updated' => $date,
'project_estimated_hours' => $this->input->post('project_estimated_hours'),
'start' => $this->input->post('start'),
'end' => $this->input->post('end'),
'owner_id' => get_current_user_id(),
);
$prefix_projects_id = $this->Project_model->update_prefix_projects($entry_id,$params);
$assignees = array(
'subdomain_id' => $this->session->userdata('subdomain'),
'project_id' => $entry_id,
'user_id' => $this->input->post('assignee'),
);
$this->load->model('Project_assignee_model');
$insertAssignees = array();
for ($i = 0; $i < count($assignees['user_id']); $i++)
{
//Get user_id from ID
$userID = $assignees['user_id'][$i];
$insertAssignees[$i] = array('project_id' => $entry_id, 'user_id' => $assignees['user_id'][$i]); // $insert is ready for insert_batch
$prefix_assignees = $this->Project_assignee_model->add_prefix_project_assignees($insertAssignees[$i]);
}
//redirect('project/index');
}
else
{
$this->load->model('Client_model');
$data['prefix_clients'] = $this->Client_model->get_all_prefix_clients();
$data['prefix_projects'] = $this->Project_model->get_prefix_projects($entry_id);
$data['prefix_users'] = $this->aauth->list_users();
$this->load->model('Project_assignee_model');
$data['prefix_assignees'] = $this->Project_assignee_model->get_prefix_project_assignees($entry_id);
$this->load->view('project/edit',$data);
}
}
Why does print_r show the correct subdomain_id but when it is saved to database it saves as 0?
*******UPDATE*******
Just for reference, this works:
$assignees = array(
'subdomain_id' => 10,
'project_id' => $entry_id,
'user_id' => $this->input->post('assignee'),
);
But this does not (Even though printing the userdata for subdomain gives me 10):
$assignees = array(
'subdomain_id' => $this->session->userdata('subdomain'),
'project_id' => $entry_id,
'user_id' => $this->input->post('assignee'),
);
Sometimes I guess it just takes writing it out for others before I realize my problem. When I loop through each assignee to add them to the table I realized I was not passing the subdomain_id with it.
I had this:
$insertAssignees[$i] = array('project_id' => $entry_id, 'user_id' => $assignees['user_id'][$i]); // $insert is ready for insert_batch
Needed to be changed to have subdomain_id included
$insertAssignees[$i] = array('subdomain_id' => $this->session->userdata('subdomain'), 'project_id' => $entry_id, 'user_id' => $assignees['user_id'][$i]); // $insert is ready for insert_batch

Upsert - php mongodb- Can't insert a new record

I'm running the following code. if the record already exists it overrides the existing fields with the new one at $updated_fields_array. But if the record doesn't exist I don't know how to add a new record with new fields ($new_fields_array). which operator should I use? Can someone help me out?
$current_time = time();
$current_mongo_date = new MongoDate($current_time);
$collection = $this->mongo->selectCollection(MONGO_NOTIFY_DB, 'AccountSettings');
$criteria_array=array("email" => $email, "name" => $name);
$updated_fields_array = array (
'last_sent' => $current_time,
'updated' => $current_mongo_date
);
$new_fields_array = array (
'created' => $current_mongo_date,
'updated' => $current_mongo_date,
'email' => $email,
'name' => $name,
'last_sent' => $current_time,
'deleted' => FALSE
);
try {
$collection->update(
$criteria_array,
array('$set' => $updated_fields_array),
array("upsert" => true)
);
} catch (MongoCursorException $mce) {
log_message('error', 'QUERY UPDATE FAILED :: AccountSettings :: ' . print_r($updated_fields_array, true) . ' :: ' . $mce->getMessage());
}
return;
Evgeny's Answer is ok but you are missing one problem
You have duplicate keys in the updated_fields_array and new_fields_array which throws MongoDB WriteException because Mongo will first create the new object and only then update it.
so change
$updated_fields_array = array (
'last_sent' => $current_time,
'updated' => $current_mongo_date
);
$new_fields_array = array (
'created' => $current_mongo_date,
'updated' => $current_mongo_date,
'email' => $email,
'name' => $name,
'last_sent' => $current_time,
'deleted' => FALSE
);
to
$updated_fields_array = array (
'last_sent' => $current_time,
'updated' => $current_mongo_date
);
$new_fields_array = array (
'created' => $current_mongo_date,
'email' => $email,
'name' => $name,
'deleted' => FALSE
);
and change the query (as Evgeny wrote or the Documentation)
$collection->update(
$criteria_array,
array('$set' => $updated_fields_array, '$setOnInsert'=> $new_fields_array),
array("upsert" => true)
);
You can use UPDATE command with upsert option and $set/$setOnInsert operators (see https://docs.mongodb.org/manual/reference/operator/update/setOnInsert/). See example below (note, that you should have unique index on {email:1,name:1})
$current_time = time();
$current_mongo_date = new MongoDate($current_time);
$collection = $this->mongo->selectCollection(MONGO_NOTIFY_DB, 'AccountSettings');
$criteria_array=array("email" => $email, "name" => $name);
$updated_fields_array = array (
'last_sent' => $current_time,
'updated' => $current_mongo_date
);
$new_fields_array = array (
'created' => $current_mongo_date,
'deleted' => FALSE
);
try {
$collection->update(
$criteria_array,
array('$set' => $updated_fields_array, '$setOnInsert'=> $new_fields_array),
array("upsert" => true)
);
} catch (MongoCursorException $mce) {
log_message('error', 'QUERY UPDATE FAILED :: AccountSettings :: ' . print_r($updated_fields_array, true) . ' :: ' . $mce->getMessage());
}
return;
I had to use updateOne
$result = $collection->updateOne(
array('first_id' => 123456,'some_number' => 333333),
array('$set' => array('some_status' => 'Delayed')),
array('upsert' => true)
);

Having issue with the line

I got this error when i upload it to the FTP,
Strict Standards: Only variables should be passed by reference in /home/user/public_html/ref/hhhhh_hhhhh/index.php on line 15
Any idea what's wrong?
<?php
require_once 'jsonRPCClient.php';
$api_key = 'apikey';
$api_url = 'url';
$client = new jsonRPCClient($api_url);
$campaigns = $client->get_campaigns(
$api_key,
array (
# find by name literally
'name' => array ( 'EQUALS' => 'test' )
)
);
$CAMPAIGN_ID = array_pop(array_keys($campaigns));
if(isset($_POST['submit']))
{
$result = $client->add_contact(
$api_key,
array (
'campaign' => $CAMPAIGN_ID,
'name' => 'Test',
'email' => 'test#test.test',
)
);
$cid = "infod";
$site_url = $cid.".pokemon.com";
header("Location: http://$site_url") ;
}
?>
$result = $client->add_contact(
$api_key,
array (
'campaign' => $CAMPAIGN_ID,
'name' => 'Test',
'email' => 'test#test.test',
)
); /* <- missed the ";" */
Try changing
$CAMPAIGN_ID = array_pop(array_keys($campaigns));
to
$CAMPAIGN_ID = array_keys($campaigns);
$CAMPAIGN_ID = array_pop($CAMPAIGN_ID);
and see if it helps.

return array of arrays nusoap php web service

i have a problem returning an array of arrays, i making a web service in php using nusoap, here is my code:
server.php
<?php
//libreria de nusoap
require_once ('nusoap/lib/nusoap.php');
$miURL = 'http://localhost/webservice/';
$server = new soap_server();
$server->configureWSDL('Web Service de Pruebas', $miURL);
$server->wsdl->schemaTargetNamespace = $miURL;
$server->wsdl->addComplexType(
'array_php',
'complexType',
'struct',
'all',
'',
array(
'pk' => array('name' => 'pk', 'type' =>'xsd:int'),
'rol' => array('name' => 'rol', 'type' =>'xsd:string'),
'descripcion' => array('name' => 'descripcion', 'type' =>'xsd:string')
)
);
$server->wsdl->addComplexType(
'array_array',
'complexType',
'array',
'',
'SOAP-ENC:Array',
array(),
array(
array('ref' => 'SOAP-ENC:arrayType',
'wsdl:arrayType' => 'tns:array_php[]'
)
),
'tns:array_php'
);
$server->register('prueba', // method name
array(), // input parameters
array('return' => 'tns:array_array'), // output parameters
$miURL, // namespace
$miURL . '#prueba', // soapaction
'rpc', // style
'encoded', // use
'Get Specific array_php' // documentation
);
function prueba()
{
$con = mysql_connect('localhost', 'root', '1234');
mysql_selectdb('laboral', $con);
$sql = "SELECT * FROM roles";
$q = mysql_query($sql);
$item = array();
while($r = mysql_fetch_assoc($q)){
$item[] = $r;
}
return $item;
}
if( !isset($HTTP_RAW_POST_DATA) )
$HTTP_RAW_POST_DATA = file_get_contents( 'php://input' );
$server->service($HTTP_RAW_POST_DATA);
?>
client.php
<?php
//libreria nusoap
require_once ('nusoap/lib/nusoap.php');
//lineas de configuracion
$serverURL = 'http://localhost/webservice/ws2.php?wsdl';
$cliente = new nusoap_client($serverURL);
//sí error de conexión:
$error = $cliente->getError();
if($error){
echo "<p> '.$error.' </p>";
echo '<p style="color:red;'>htmlspecialchars($cliente->getDebug(), ENT_QUOTES).'</p>';
die();
}
echo "<br/>";
$arreglo2 = $cliente->call('prueba');
echo "<br/>";
for( $i=0; $i<3; $i++ ){
print_r( $arreglo2[$i]['pk'] );
print_r( $arreglo2[$i]['rol'] );
print_r( $arreglo2[$i]['descripcion'] );
echo "<br/>";
}
?>
the problem is the return, is returning nothing to my client and i dont know what happens, i been reading a lot of forums but i cant find a answer, please if some one know about help me here
ty and sorry for my english
This is what I did:
// Complex Array Keys and Types ++++++++++++++++++++++++++++++++++++++++++
$server->wsdl->addComplexType('notaryConnectionData','complexType','struct','all','',
array(
'id' => array('name'=>'id','type'=>'xsd:int'),
'name' => array('name'=>'name','type'=>'xsd:string')
)
);
// *************************************************************************
// Complex Array ++++++++++++++++++++++++++++++++++++++++++
$server->wsdl->addComplexType('notaryConnectionArray','complexType','array','','SOAP-ENC:Array',
array(),
array(
array(
'ref' => 'SOAP-ENC:arrayType',
'wsdl:arrayType' => 'tns:notaryConnectionData[]'
)
)
);
// *************************************************************************
// This is where I register my method and use the notaryConnectionArray
$server->register("listNotaryConnections",
array('token' => 'xsd:string'),
array('result' => 'xsd:bool', 'notary_array' => 'tns:notaryConnectionArray', 'error' => 'xsd:string'),
'urn:closingorder',
'urn:closingorder#listNotaryConnections',
'rpc',
'encoded',
'Use this service to list notaries connected to the signed-in title company.');
// In my function, I query the data and do:
$list = array();
$results = mysql_query($query);
while($row = mysql_fetch_assoc($results)) {
array_push($list, array('id' => intval($row['na_id']), 'name' => $row['agency_name']));
}
return array("result" => true, "notary_array" => $list);
// The output is:
Array
(
[result] => 1
[notary_array] => Array
(
[0] => Array
(
[id] => 1
[name] => Agency 1
)
[1] => Array
(
[id] => 3
[name] => Agency 3
)
[2] => Array
(
[id] => 4
[name] => Agency 4
)
)
[error] =>
)
Hope this helps.

Categories