CodeIgniter - Changing normal SQL into CI's own language - sql

Can someone show me how to change the following SQL into CI's active stuff.
$query = $this->db->query('UPDATE pollanswers SET pollAnswerPoints = pollAnswerPoints + 1 WHERE pollAnswerID = '.$pollanswerid.'');
return true;
Also, how would i add an if statement to that to see if it completed properly return true, if not return false?
Cheers,

try this
$this->db->set('pollAnswerPoints', 'pollAnswerPoints + 1', FALSE);
$this->db->where('pollAnswerID', $pollanswerid);
$this->db->update('pollanswers');
Edit:
if($this->db->affected_rows() > 0)
{
return true;
} else
{
return false;
}

Related

resize of image not working in codeigniter 3

I've been attempting to resize a image in codeigniter 3 ,but no luck! I have the resize inside the ddoo_upload() function , the resize() will work , when it comes to one image field within that form and if you will add two image field within that form , then the resize() will not work. Not sure what is wrong!
This is what i have tried for image upload,The code below shows my upload function (and resize within it)
if (isset($_FILES['destiimg']) && $_FILES['destiimg']['name'] != '') {
$filename = $this->ddoo_upload('destiimg', '2000' , '336');
} else {
$filename = NULL;
}
if (isset($_FILES['destiimg_thumb']) && $_FILES['destiimg_thumb']['name'] != '') {
$destbannerthumb_imgnew = $this->ddoo_upload('destiimg_thumb', 300 , 225);
} else {
$destbannerthumb_imgnew = NULL;
}
function ddoo_upload($filename, $width, $height)
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'jpg|jpeg|png|gif';
$config['overwrite'] = FALSE;
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload($filename)) {
echo $this->upload->display_errors();die();
return NULL;
} else {
$data = $this->upload->data();
$filename = $data['file_name'];
$config1['image_library'] = 'gd2';
$config1['source_image'] = $this->upload->upload_path.$this->upload->file_name;
//$config1['create_thumb'] = TRUE;
$config1['maintain_ratio'] = FALSE;
$config1['width'] = $width;
$config1['height'] = $height;
$this->load->library('image_lib', $config1);
$this->image_lib->resize();
return $filename;
}
}
The upload works fine , but the resize has some issue.
You are missing some config options when loading image_lib.
Look at the manual, you didn't specified source_image (and other options).
If you want to use something advanced, there is good library called Image Moo. It's older but good working with CI3.

Aurelia refresh property dependencies

Validate if checkbox should be displayed in html page:
get canPerformCommand() {
let r = false;
let valids = ['Success', 'Error'];
if (this.requests.length == 0) return false;
if (valids.indexOf(this.myresult[0].requestStatus) > 0) {
r = true;
}
return r;
}
Html page:
<span if.bind="canPerformCommand" class="panel-heading-buttons">
<button click.trigger="confirm()">Confirm</button>
</span>
Search:
return this.myService.getRequests()
.then(data => {
this.requests = data
//Somehow refresh canPerformCommand here?
});
this.requests will be empty on first page load, resulting in canPerformCommand = false.
I want to refresh canPerformCommand when using the search function.
Currently canPerformCommand will not refresh itself after a search has been done.
How do I refresh canPerformCommand after search using Property Dependencies?
Solution:
The easiest and most logical solution would be to change canPerformCommand into two separate entities -- a flag variable and a function. Make the flag variable be canPerformCommand and keep the if.bind=canPerformCommand but change the name of your function to updateCanPerformCommand() so that you can easily call this function from your return this.myService.getRequests() .then function.
Details:
Set up your view-model like this:
export class App { // <-- (or whatever yours is called)
canPerformCommnad = false;
constructor() {
// ...
}
updateCanPerformCommand() {
let r = false;
let valids = ['Success', 'Error'];
if (this.requests.length == 0) {
this.canPerformCommand = false;
} else if (valids.indexOf(this.myresult[0].requestStatus) > 0) {
this.canPerformCommand = true;
}
}
}
I believe you need to change myresult to requests in the canPerformCommand getter:
get canPerformCommand() {
let r = false;
let valids = ['Success', 'Error'];
if (this.requests.length == 0) return false;
if (valids.indexOf(this.requests[0].requestStatus) > 0) {
r = true;
}
return r;
}
Since this getter will be dirty checked by Aurelia, it will be called every 200ms. To avoid that, you can add a computedFrom decorator:
import {computedFrom} from 'aurelia-framework';
export class MyClass {
....
#computedFrom('requests')
get canPerformCommand() { ....
I replaced:
if (valids.indexOf(this.myresult[0].requestStatus) > 0) {
r = true;
}
With
if (valids.includes(this.requests[0].requestStatus)) {
r = true;
}
And now it works. I was using the indexOf function on other pages aswell, and strangely enough it worked on most of them. Must have been something wrong in my model.
Also, I agree that it would be better to use computedFrom.

Call to a member function on non object in CodeIgniter

I'm trying to validate an username and check if this already exists in the system. Now the problem's that I've the user list in the table: ea_user
and the user settings in the table: ea_user_settings. Now:
ea_user > contain the id of the user that isn't remove from the system, the field 'data'
ea_user_settings > contain the username
So my function is this:
public function validate_username($username, $user_id)
{
$num_rows = $this->db->join('ea_user_settings', 'ea_user_settings.id = ea_user.id', 'inner')
->get_where('ea_user_settings',
array('username' => $username, 'id_users <> ' => $user_id, 'ea_user.data' => 0))->num_rows();
return ($num_rows > 0) ? FALSE : TRUE;
}
The problem's I get this error:
Fatal error: Call to a member function num_rows() on a non-object
Try this
public function validate_username($username, $user_id)
{
$this->db->select(*);
$this->db->from('table_name');
$this->db->join('ea_user_settings', 'ea_user_settings.id = ea_user.id', 'inner')
$this->db->get_where('ea_user_settings', array('username' => $username, 'id_users <> ' => $user_id, 'ea_user.data' => 0));
$query = $this->db->get();
$result = $query->result_array(); # add this
$count = count($result);
if (!empty($count)) {
return true;
}
else{
return false;
}
}
}
It isn't documented, but any of the get() functions (get_where() in your case) can return FALSE. (Learned this the hard way.) That would seem to be your problem. FALSE->num_rows() has no meaning as FALSE is not a object.
This usually happens because the query does not build correctly.
The compiled query can be examined by doing this.
public function validate_username($username, $user_id)
{
$this->db->select(*)
->from('ea_user_settings')
->join('ea_user_settings', 'ea_user_settings.id = ea_user.id', 'inner')
->where(array('username' => $username, 'id_users <> ' => $user_id, 'ea_user.data' => 0));
$compiled_select = $this->db->get_compiled_select(NULL, FALSE);
//inspect or var_dump($compiled_select) to see what query statement was built.
After setting up all the join, where and other pieces of a query I have taken to checking the truthiness of get() before using its return. In your case something like this. Code picks up after (or instead of) the line $compiled_select = $this->...
if($query = $this->db->get())
{
return ($query->num_rows() > 0) ? FALSE : TRUE;
}
else
{
throw new Exception("get call returned FALSE");
}
}
For me, the Exception is useful mostly during development. But you could put your call to the validate_username() in a try catch block if it would be useful.

Joomla onUserAuthenticate

In the Joomla source, I found a method caled onUserAuthenticate, which could not be found in the API (through google), but its functionality is the similar to onLoginUser... So, after login/password check I need to run some more code via this function. As a result, I have true/false - depending on it I need to set users' authorization completely. Even if the user's login/password is correct, but my code returns false -> authorization fail...
I am trying something like:
functionon UserAuthenticate($credentials,$options,&$response){
jimport('joomla.user.helper');
$username=mysql_real_escape_string($credentials['username']);
$password=mysql_real_escape_string(md5($credentials['password']));
//my code returns $result
if($result!=NULL){
$response->status=JAUTHENTICATE_STATUS_SUCCESS;
$response->error_message='';
}
else{
$response->status=JAUTHENTICATE_STATUS_FAILURE;
$response->error_message=JText::_('JGLOBAL_AUTH_INVALID_PASS');
}
}
onUserAuthenticate is an event not a method. You use plugins to listen for Joomla events, in this case usually a user plugin would listen for this. When the event happens your code will run.
http://docs.joomla.org/Plugin
You can try this for custom login form-
$app = JFactory::getApplication();
$data = array();
$data['return'] = '';
$data['username'] = JRequest::getVar('username', '', 'method', 'username');
$data['password'] = JRequest::getString('password', '', 'post', JREQUEST_ALLOWRAW);
// Get the log in options.
$options = array();
// Get the log in credentials.
$credentials = array();
$credentials['username'] = $data['username'];
$credentials['password'] = $data['password'];
// Perform the log in.
$error = $app->login($credentials, $options);
if (!JError::isError($error)) {
$response->status=JAUTHENTICATE_STATUS_SUCCESS;
$response->error_message='';
}else{
$response->status=JAUTHENTICATE_STATUS_FAILURE;
$response->error_message=JText::_('JGLOBAL_AUTH_INVALID_PASS');
}
If you want authenticate solution on function "onUserAuthenticate" you should check it yourself if user credential is valid or not And you do it with this code :
function onUserAuthenticate($credentials, $options, &$response)
{
$response->type = 'Joomla';
// Joomla does not like blank passwords
if (empty($credentials['password'])) {
$response->status = JAuthentication::STATUS_FAILURE;
$response->error_message = JText::_('JGLOBAL_AUTH_EMPTY_PASS_NOT_ALLOWED');
return false;
}
// Initialise variables.
$conditions = '';
// Get a database object
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('id, password');
$query->from('#__users');
$query->where('username=' . $db->Quote($credentials['username']));
$db->setQuery($query);
$result = $db->loadObject();
if ($result) {
$parts = explode(':', $result->password);
$crypt = $parts[0];
$salt = #$parts[1];
$testcrypt = JUserHelper::getCryptedPassword($credentials['password'], $salt);
if ($crypt == $testcrypt) {
$user = JUser::getInstance($result->id); // Bring this in line with the rest of the system
$response->email = $user->email;
$response->fullname = $user->name;
$response->status = JAuthentication::STATUS_SUCCESS;
$response->error_message = '';
print_r("You login correct Sir");
die();
} else {
print_r("you enter wrong credential");
die();
$response->status = JAuthentication::STATUS_FAILURE;
$response->error_message = JText::_('JGLOBAL_AUTH_INVALID_PASS');
}
} else {
print_r("you enter blank credential");
die();
$response->status = JAuthentication::STATUS_FAILURE;
$response->error_message = JText::_('JGLOBAL_AUTH_NO_USER');
}
return true;
}

codeigniter pagination for a query

So far found plenty of help to get the pagination working for a get(table) command.
What I need is to pick only few of the entries from a couple of linked tables based on a sql where statement.
I guess the query command is the one to use but in this case how do I do the pagination since that command does not take extra parameters such $config['per_page']
Thanks for the help
Without any more info to go on I think that what you're looking for is something like the following.
public function pagination_example($account_id)
{
$params = $this->uri->ruri_to_assoc(3, array('page'));
$where = array(
'account_id' => $account_id,
'active' => 1
);
$limit = array(
'limit' => 10,
'offset' => (!empty($params['page'])) ? $params['page'] : 0
);
$this->load->model('pagination_model');
$data['my_data'] = $this->pagination_model->get_my_data($where, $limit);
foreach($this->uri->segment_array() as $key => $segment)
{
if($segment == 'page')
{
$segment_id = $key + 1;
}
}
if(isset($segment_id))
{
$config['uri_segment'] = $segment_id;
}
else
{
$config['uri_segment'] = 0;
}
$config['base_url'] = 'http://'.$_SERVER['HTTP_HOST'].'/controller_name/method_name/whatever_your_other_parameters_are/page/';
$config['total_rows'] = $this->pagination_model->get_num_total_rows();// Make a method that will figure out the total number
$config['per_page'] = '10';
$this->load->library('pagination');
$this->pagination->initialize($config);
$data['pagination'] = $this->pagination->create_links();
$this->load->view('pagination_example_view', $data);
}
// pagination_model
public function get_my_data($where = array(), $limit = array())
{
$this->db
->select('whatever')
->from('wherever')
->where($where)
->limit($limit['limit'], $limit['offset']);
$query = $this->db->get();
if($query->num_rows() > 0)
{
$data = $query->result_array();
return $data;
}
return FALSE;
}
This should at least get you on the right track
If this isn't what you're asking I'd happy to help more if you can be a little more specific. How about some of your code.
The only other options that I can think of would be to either code a count in your select statement or not limit the query and use array_slice to select a portion of the returned array.