Moodle Error writing to database - moodle

I am getting Error writing to database in moodle:
Code:
if (is_siteadmin()) {
class addschedule_form extends moodleform {
function definition () {
$mform =& $this->_form;
$mform->addElement('text', 'id', 'Enter ID:');
$mform->setType('id', PARAM_TEXT);
$this->add_action_buttons(true, 'submit');
}
}
$ti_form = new addschedule_form();
$ti_form->get_data();
if ($ti_form->is_cancelled()) {redirect('index.php');}
if ($recs = $ti_form->get_data()) {
$deleteit = $DB -> delete_records('DELETE * FROM `mdl_schedules` WHERE id = ' . $recs -> id . '');
redirect('schedule.php');
}
}
else { }
$ti_form->display();
What could be the reason? Any reference or help will be much appreciated.
Regards

The syntax is
$DB->delete_records('schedules', array('id' => $recs->id));
You might want to keep this open in a tab for reference - https://docs.moodle.org/dev/Data_manipulation_API

Related

advcheckbox in moodle form is storing only 0 in database

I am new Moodle and working on form data saving. I have created a group of checkbox which will take some input from the users and store it to the database, but unfortunately it is storing only 0/1 in the database. I have no clue where I made the mistake.
This my php file where I added the form field-
class custom_signup_form extends moodleform {
//Add elements to form
public function definition() {
global $CFG;
global $DB;
$mform = $this->_form; // Don't forget the underscore!
//$mform->addElement('text', 'email', get_string('email')); // Add elements to your form.
//$mform->setType('email', PARAM_NOTAGS); // Set type of element.
//$mform->setDefault('email', 'Please enter email'); // Default value.
if($this->content !== Null){
return $this->content;
}
$courses = $DB->get_records('course');
$categories = $DB->get_records('course_categories');
$interestedcourse=array();
foreach($courses as $course){
$coursestring = $course->fullname;
$interestedcourse[] = $mform->createElement('advcheckbox', 'interestedcourse[]','', $coursestring, array('group' => 1), array('',$coursestring));
}
$mform->addGroup($interestedcourse, 'interestedcoursegroup', get_string('interestedcourse', 'assignsubmission_metadata'),array('<br>'), false);
$interestedcategory=array();
foreach($categories as $category){
$categorystring = $category->name;
$interestedcategory[] = $mform->createElement('advcheckbox', 'interestedcategory[]','', $categorystring, array('group' => 1), array('',$categorystring));
}
$mform->addGroup($interestedcategory, 'interestedcategorygroup', get_string('interestedcategory', 'assignsubmission_metadata'),array('<br>'), false);
$this->add_action_buttons();
This is the php file for saving form data-
require_once(__DIR__ . '/../../config.php');
require_once($CFG->dirroot . '/local/custom_signup/classes/form/edit.php');
global $DB;
$PAGE->set_url(new moodle_url('/local/custom_signup/signupform.php'));
$PAGE->set_title(get_string('custom_signup', 'local_custom_signup'));
#custom form for signup
$mform = new custom_signup_form();
if ($mform->is_cancelled()) {
// Go back to manage.php page
redirect($CFG->wwwroot . '/local/custom_signup/manage.php', get_string('cancelled_form', 'local_message'));
}
else if ($fromform = $mform->get_data()) {
var_dump($fromform);
die;
}
echo $OUTPUT->header();
$mform->display();
echo $OUTPUT->render_from_template('local_custom_signup/signupform', $templatecontext);
echo $OUTPUT->footer();
object returned from the form submission-
object(stdClass)#288 (3) { ["interestedcourse"]=> array(1) { [""]=> string(0) "" } ["interestedcategory"]=> array(1) { [""]=> string(0) "" } ["submitbutton"]=> string(12) "Save changes" }

CodeIgniter Suddenly Cannot Upload Image and says Cannot Be Null

Greeting everyone and especially to Senior of CodeIgniter Developer.
I have a problem with website that was built from CodeIgniter (I am not the developer inherited by previous epmployer). This website cannot working properly, especially when upload the image and shows warning about
Error Number: 1048 Column 'article_image' cannot be null
I did try with find the problem on the script and database, but nothing change and because no one change the codes & contents. Today, i try again with changing the "Null into yes" (previously is "No"), and tried to upload the article. It is miracle that it is working but the next problem is the image is gone (broken). I search at other and looking people with same problem with me says that i need to upgrade the CodeIgniter. Mine is 3.0.0 while the latest is 3.1.10. I copy paste the content inside /System and /views/error/cli not making better but make it worse, the image at the web page is gone(missing).
This is my Article_model
defined('BASEPATH') OR exit('No direct script access allowed');
class Article_model extends CI_Model {
public function get_all()
{
// $this->db->order_by('article_date', 'desc');
// $this->db->order_by('article_view', 'desc');
// $query = $this->db->get_where('article', array('flag !=' => 3));
// return $query->result_array();
$query = $this->db->query("SELECT A.*,B.*, A.id AS id_article FROM article AS A JOIN category B ON A.article_category = B.id WHERE A.flag != 3 ORDER BY article_date DESC, article_view DESC ");
return $query->result_array();
}
public function check($article_id)
{
$query = $this->db->get_where('article', array('flag !=' => 3, 'id' => $article_id));
return $query->row_array();
}
public function get_category()
{
$query = $this->db->order_by('category_name', 'ASC')->get_where('category', array('flag' => 1));
return $query->result_array();
}
public function get_tag()
{
$query = $this->db->order_by('tag_name', 'ASC')->get_where('tag', array('flag' => 1));
return $query->result_array();
}
public function get_selected_tag($article_id)
{
$query = $this->db
->select('tag.id, tag_name')
->join('article_tag', 'tag_id = tag.id')
->where(array('tag.flag' => 1, 'article_id' => $article_id))
->get('tag');
return $query->result_array();
}
public function insert()
{
$this->load->helper('upload');
$this->load->library('image_moo');
$image = file_upload('article_image', 'upload/article');
$this->image_moo->load($image['full_path']);
$this->image_moo->resize(924, 527)->save($image['path'] . '/' . $image['file_name'], TRUE);
$this->image_moo->resize_crop(100, 69)->save($image['path'] . '/thumb/' . $image['file_name']);
$this->image_moo->resize_crop(367, 232)->save($image['path'] . '/cover/' . $image['file_name']);
$insert_data = array(
'article_author' => $this->session->admin_id,
'article_title' => $this->input->post('article_title'),
'article_slug' => url_title($this->input->post('article_title'), '-', TRUE),
'article_category' => $this->input->post('article_category'),
'article_image' => $image['file_name'],
'article_content' => $this->input->post('article_content'),
'is_popup' => $this->input->post('is_poup'),
'article_date' => $this->input->post('article_date'),
);
$this->db->insert('article', $insert_data);
$article_id = $this->db->insert_id();
foreach ($this->input->post('article_tag') as $tag)
{
// Check apakah tag itu udah ada di database?
if (is_numeric($tag))
{
$tag_id = $tag;
}
else
{
$this->db->insert('tag', array('tag_name' => strtolower(trim($tag)), 'tag_slug' => url_title(trim($tag), '-', TRUE)));
$tag_id = $this->db->insert_id();
}
if ( ! $this->db->get_where('article_tag', array('article_id' => $article_id, 'tag_id' => $tag_id))->row_array())
{
$this->db->insert('article_tag', array('article_id' => $article_id, 'tag_id' => $tag_id));
}
}
}
public function update($id)
{
$this->load->helper('upload');
$this->load->library('image_moo');
$image = file_upload('article_image', 'upload/article');
$this->image_moo->load($image['full_path']);
$this->image_moo->resize(924, 527)->save($image['path'] . '/' . $image['file_name'], TRUE);
$this->image_moo->resize_crop(100, 69)->save($image['path'] . '/thumb/' . $image['file_name']);
$this->image_moo->resize_crop(367, 232)->save($image['path'] . '/cover/' . $image['file_name']);
$insert_data = array(
'article_author' => $this->session->admin_id,
'article_title' => $this->input->post('article_title'),
'article_slug' => url_title($this->input->post('article_title'), '-', TRUE),
'article_category' => $this->input->post('article_category'),
'is_popup' => $this->input->post('is_popup'),
'article_content' => $this->input->post('article_content'),
'article_date' => $this->input->post('article_date'),
);
if ($image)
{
$insert_data['article_image'] = $image['file_name'];
}
$article_id = $id;
$this->db->where('id', $id);
$this->db->update('article', $insert_data);
$this->db->where('article_id', $id);
$this->db->delete('article_tag');
foreach ($this->input->post('article_tag') as $tag)
{
// Check apakah tag itu udah ada di database?
if (is_numeric($tag))
{
$tag_id = $tag;
}
else
{
$this->db->insert('tag', array('tag_name' => strtolower(trim($tag)), 'tag_slug' => url_title(trim($tag), '-', TRUE)));
$tag_id = $this->db->insert_id();
}
if ( ! $this->db->get_where('article_tag', array('article_id' => $article_id, 'tag_id' => $tag_id))->row_array())
{
$this->db->insert('article_tag', array('article_id' => $article_id, 'tag_id' => $tag_id));
}
}
}
}
What should i do guys? i did backup but it remain same like after upgraded. Thank you. Web Url (http://www.hidupseimbangku.com/)
First. If you want to upgrade CI Version you must follow Upgrading Guide one by one. There may be break changes and you need to correct them, you can find this guide here:
https://www.codeigniter.com/userguide3/installation/upgrading.html
I suggest you rollback upgrade changes and start again doing one by one. It is not hard, it is just time consuming.
The error you're getting is probably related to an error of uploading process. What is file_upload?
I also suggest you read this, for properly file upload.

The server don't receive a Response / SendRequests

Iam new guy for Zend2 framework...I got an error which I didnt trace it...
Iam writing a controller named 'usertask' and in that fir index function i wrote the code like this
public function indexAction()
{
$sendRequest = new SendRequests;
$tableGrid = new DynamicTable();
$prop = array(
'customRequest' => 'GET',
'headerInformation' => array('environment: development', 'token_secret: abc')
);
$returnRequest = $sendRequest->set($prop)->requests('http://service-api/usertask');
$returnData = json_decode($returnRequest['return'],true);
$tableGrid->tableArray = $returnData['result'];
$dynamicTable = $tableGrid->tableGenerate();
$view = new ViewModel(array(
'usertask' => $dynamicTable
));
//print_r($view);exit;
return $view;
}
but it is not listing my usertasks...while Iam printing $returnRequest its giving me error message like
The server don't receive a Response / SendRequests
what it the mistake in my code...could anyone suggest me...please..iam using "zend2"
Sorry guys I found my mistake ...I got big code but I need something like
public function indexAction()
{
$view = new ViewModel(array(
'usertask' => $this->UserTable()->fetchall(),
));
return $view;
}
public function getUserTable()
{
if (!$this->userTable) {
$sm = $this->getServiceLocator();
$this->userTable = $sm->get('User\Model\UserTable');
}
return $this->userTable;
}
that's it...i got it as a list of users

Identity and Credential in different tables. How to login user?

I'm using Zend Framework.
I save users information in two tables.
I have one table for his basic information and password, and in the other table I save his e-mails.
He can login with any e-mail.
My question is how should I extend Zend_Auth_Adapter_DbTable so that I can allow this?
I prefer not to use table views.
[edit]
I found a solution. What worked for me:
class My_Auth_Adapter_DbTable extends Zend_Auth_Adapter_DbTable
{
protected function _authenticateCreateSelect()
{
// build credential expression
if (empty($this->_credentialTreatment) || (strpos($this->_credentialTreatment, '?') === false)) {
$this->_credentialTreatment = '?';
}
$credentialExpression = new Zend_Db_Expr(
'(CASE WHEN ' .
$this->_zendDb->quoteInto(
$this->_zendDb->quoteIdentifier($this->_credentialColumn, true)
. ' = ' . $this->_credentialTreatment, $this->_credential
)
. ' THEN 1 ELSE 0 END) AS '
. $this->_zendDb->quoteIdentifier(
$this->_zendDb->foldCase('zend_auth_credential_match')
)
);
// get select
//$dbSelect = clone $this->getDbSelect();
$mdl = new My_Model_Db_Table_Users();
$dbSelect = $mdl->select();
$dbSelect = $dbSelect->setIntegrityCheck(false);
$dbSelect = $dbSelect->from(array('u' => $this->_tableName), array('*', $credentialExpression));
$dbSelect = $dbSelect->joinInner(array('ue' => 'users_emails'), 'ue.id_user = u.user_id', array('user_email'));
$dbSelect = $dbSelect->where('ue.' . $this->_zendDb->quoteIdentifier($this->_identityColumn, true) . ' = ?', $this->_identity);
return $dbSelect;
}
}
I explained what did it for me in the question.
But, to repeat, easiest for me was to change Zend_Auth_Adapter_DbTable::_authenticateCreateSelect().
There are a method named Zend_Auth_Adapter_DbTable::getDbSelect returns Zend_Db_Select object.
Call it and then you can join those two tables.
Hope this help.
Regards,
Ahmed B.
Here's an alternate method.
Extend the Zend_Auth_Adapter_DbTable class.
class My_Auth_Adapter_DbTable extends Zend_Auth_Adapter_DbTable {
public function setDbSelect($select) {
$this->_dbSelect = $select;
return $this;
}
}
Create instance of your new adapter
$authAdapter = new My_Auth_Adapter_DbTable(
$this->dbTable->getAdapter()
, 'Users'
, 'Users.username'
, 'Users.password'
);
In your Application_Model_DbTable_Users class, create a method that returns the select object with the joined tables.
public function getSelectAuth() {
$select = $this
->select()
->setIntegrityCheck(false)
->from(array('SystemPeopleJoined' => $this->_name)
, array(
'id'
, 'person_id'
, 'system_role_id'
, 'created_on'
, 'expires_on'
)
)
->joinInner(
'People'
, 'People.id = SystemPeopleJoined.person_id'
, array(
'first_name' => 'first_name'
, 'last_name' => 'last_name'
, 'name' => "CONCAT_WS(' ', `People`.`first_name`, `People`.`last_name`)"
)
return $select;
}
Set the select object in your adapter
$select = $this->dbTable->getSelectAuth();
$authAdapter
->setDbSelect($select)
->setIdentity($params['username'])
->setCredential($params['password'])
->setCredentialTreatment("SHA1(?)")
;

Zend_Form not displaying error message with calling addError

I am implementing an updatePasswordAction and its not displaying an error with an invalid current password. I could not implement this with a Zend_Validate class to use with a supplied record->password, so i just validated for now in my controller action and if failed then i add the error message to the form element. this is just before i run $form->isValid. In any case, its working. but when the validation fails, its not displaying the error message on this on the element. any help would be greatly appreciated.
FYI: When I submit a blank current password, it shows the validation
class Admin_Form_UserPassword extends Katana_Form
{
public function init()
{
$element = $this->createElement('hidden', 'id');
$this->addElement($element);
$element = $this->createElement('password','password');
$element->setLabel('Current Password:');
$element->setRequired(true);
$this->addElement($element);
$element = $this->createElement('password','new_password');
$element->setLabel('New Password:');
$element->addValidator('StringLength', false, array(6,24));
$element->setRequired(true);
$element->addValidator('NotEmpty');
$this->addElement($element);
$element = $this->createElement('password','new_password_confirm');
$element->setLabel('Confirm:');
$element->addValidator('StringLength', false, array(6,24));
$element->addValidator('IdenticalField', false, array('new_password', 'Confirm Password'));
$element->setRequired(true);
$this->addElement($element);
$this->addElement('submit', 'submit', array('label' => 'Submit'));
}
}
public function updatePasswordAction()
{
$resourceModel = new Core_Model_Resource_User();
$form = new Admin_Form_UserPassword();
$form->setMethod(Katana_Form::METHOD_POST);
$form->setAction($this->getActionUrl('update-password'));
if($this->getRequest()->isPost()){
$id = $this->getRequest()->getParam('id');
$record = $resourceModel->find($id)->current();
$currPassword = $record->password;
$typedPassword = md5($this->getRequest()->getParam('password'));
if($currPassword !== $typedPassword){
$form->getElement('password')->addError('Current password is incorrect.');
}
if($form->isValid($_POST)){
$data = $form->getValues();
$result = $resourceModel->updatePassword($id, $data['new_password']);
if($result){
$this->redirectSimple('list');
}
}
} else {
$id = $this->getRequest()->getParam('id');
$recordData = array(
'id' => $id
);
$form->populate($recordData);
}
$this->getView()->form = $form;
}
Adding an error to the element doesn't cause the form itself to then be invalid.
There are at least 2 methods I use to get around this:
if($currPassword !== $typedPassword){
$form->getElement('password')->addError('Current password is incorrect.');
$form->markAsError();
}
// or
if ($form->isValid($_POST) && 0 == sizeof($form->getMessages()) {
// form was valid, and no errors were set on elements
}
To clarify, when you add the error to the form ELEMENT, there is an error attached to that element, but Zend_Form::isValid only runs the validators and sets appropriate errors, it doesn't check to see if you had set an error on a particular element.
You can however call $form->getMessages() to get all the error messages attached to the form or its child elements. If this is 0 and you have validated your form, then it means there were no errors. If your form passed isValid but you added an error to an element, it will include the error message you added.
I made it work this way.
Controller:
if ($trial->getKind() != 'debt' && $_POST['kind'] == 'debt')
{
$editForm->getElement('kind')->markAsError();
}
if ($editForm->isValid($_POST)) { ... }
Form:
public function isValid($data)
{
$valid = parent::isValid($data);
if ($this->getElement('kind')->hasErrors()) {
$this->getElement('kind')->addError($this->_translate->translate('You can\'t change trial kind to debt.'));
$valid = false;
}
return $valid;
}
And this comment helped me.