---------------START-UPDATE-----------------
I added the session in the code and did not logout then login to refresh the variable .. my bad, thanks guy.
---------------END-UPDATE-----------------
I am using Codeigniter 3.0, I can read the session data, I have tested this by a echo. however when i try to insert into the table I get this error.
Error
Error Number: 1054
Unknown column 'LoginID' in 'field list'
INSERT INTO `Report_Comments` (`Comments`, `ReportID`, `LoginID`) VALUES (',l;', '53', NULL)
Filename: models/report/Report_model.php
Line Number: 58
Code (Model)
function create_comment()
{
$new_comment = array(
'Comments' => $this->input->post('Comments'),
'ReportID' => $this->input->post('ReportID'),
'UserID' => $this->session->userdata('LoginID')
);
$insert = $this->db->insert('Report_Comments', $new_comment);
return $insert;
}
It is always a good idea to double check that you have values assigned to variables before you use them. This revised model function provides some checking.
function create_comment()
{
$comments = $this->input->post('Comments');
$reportID = $this->input->post('ReportID');
$userID = $this->session->userdata('LoginID');
if(isset($reportID) && isset($userID))
{
$new_comment = array(
'Comments' => isset($comments) ? $comments : "",
'ReportID' => $reportID,
'UserID' => $userID
);
return $this->db->insert('Report_Comments', $new_comment);
}
return FALSE;
}
The above operates with the idea that the insert should not be attempted unless the ReportID and UserID values are set with some value. If no comments are present then an empty string will be save to the db.
Related
Im trying use "$this->input->post();" of Codeigniter to do not need specify each field in my form. But im getting troubles when try insert into Database.
Look my controller:
public function cadastrar(){
$var = $this->input->post(null, TRUE);
$this->load->model('m_clientes');
$this->m_clientes->inserir($var);
}
My controller is simplified here because i know how to handle database in codeigniter.
The result of this post was:
Array ( [nome] => Raphael [sobrenome] => Schubert [cpf] => 893.528.432-89 [rg] => 4529875231908472 [telefone] => (53) 2980-5792 [celular] => (53) 9 2180-7529 [rua] => Israel de Almeida [numero] => 859 [cep] => 88.312-000 [bairro] => São Vicente [cidade] => ITAJAÍ [estado] => Santa Catarina [email] => rfswdp#gmail.com [tipo] => pf [cnpj] => 34.827.481/2834-78 [inscricaoestadual] => 34120489032814930128 [razaosocial] => Teste [nomefantasia] => Disney [dataaberturaempresa] => 10/21/15 [proprietario] => Marcos Aurelio )
I normaly use this way to insert:
$data = array(
'user_name' => $this->input->post('user_name',TRUE);
'user_phone' => $this->input->post('user_phone',TRUE);
'user_role' => $this->input->post('user_role',TRUE);
);
$this->name_of_model->inserir($data);
And works...
But i was trying to use just $this->input->post(); to get all fields from form. Because my actualy application will have hundreds of fields and i was trying to do not write each line.
So my model actually was:
public function inserir($var){
if($var!=NULL):
print_r($var);
$this->db->insert('tb_usuarios',$var);
endif;
}
But i`m getting and error saying:
Message: Undefined property: Clientes::$db
and
Message: Call to a member function insert() on null
My table name is: "tb_usuarios"
I changed all fields in database to accept NULL to see if i`m get some field name wrong... but not work...
Any tips??
There is no need to catch the POST var inside $var. You can see POST variable inside the model very well. So all you need to do in the controller is:
public function cadastrar(){
$this->load->model('m_clientes');
$this->m_clientes->inserir();
}
,and inside your model:
public function inserir(){
if( count($this->input->post()) > 0):
$this->db->insert('tb_usuarios',$this->input->post());
endif;
}
The fields names in your form must correspond to the column names inside your table.
The message Message: Call to a member function insert() on null means you forgot to load the database library, just like remiheens said.
But my advice is, to use form validation for your fields, so you may be sure all necessary fields are completed using the required data format for each one of them. Although this may require allot of coding, there is no other safe way from errors on database operations. You cannot trust the user to insert the data correctly, that's why you need form validation.
In here $var = $this->input->post(null, TRUE); you use null. null is not valid input name. name = ''
and this will works $this->input->post('user_name',TRUE);
cz of it has input tag name (name = 'user_name').
We use ,TRUE) next to input post field to allows XSS Protection
$var = $this->input->post(null, TRUE); Is Wrong
while you trying this, it shows
Message: Undefined property: Clientes::$db and Message: Call to a member function insert() on null.
will not work
public function cadastrar(){
$var = $this->input->post(null, TRUE);//will never give valid response
$this->load->model('m_clientes');
$this->m_clientes->inserir($var);
}
Works well
public function cadastrar(){
$this->load->model('m_clientes');
$data = array(
'user_name' => $this->input->post('user_name',TRUE);
'user_phone' => $this->input->post('user_phone',TRUE);
'user_role' => $this->input->post('user_role',TRUE);
);
$this->name_of_model->inserir($data);
$this->load->model('m_clientes');
}
This is because your database isn't loaded into codeigniter instance. ($this->db)
Just try to autoload "database" library (config/autoload.php) or load/connect your database in your model with :
$this->load->database();
Don't forget to edit your config/database.php ;)
I handle hundreds of fields everytime but I also validate basically each one. I always do this:
$customer['name'] = $this->input->post('customer_name');
$customer['age'] = $this->input->post('customer_age');
$customer['country'] = $this->input->post('customer_country');
$customer['city'] = $this->input->post('customer_city');
// validations
if(isAgeValid($customer['age']) == FALSE)
{
echo 'Hold on, your age...hmm check it out!';
return;
}
$this->customers_model->add($customer);
The function that handles the insertion only has this:
public function add($data)
{
$data = $this->security->xss_clean($data);
$this->db->insert('customers', $data);
return $this->db->insert_id();
}
Pretty clean and simple. Now, if you don't want to validate the fields or just want to validate some of them and want to insert the others without validation this is what I purpose based on the previous code:
// validations..
if(isAgeValid());
$customer = array();
foreach($_POST as $key => $value)
$customer[$key] = $value;
$this->customers_model->add($customer);
$data = array(
'user_name' => $this->input->post('user_name');
'user_phone' => $this->input->post('user_phone');
'user_role' => $this->input->post('user_role');
);
$this->load->model('name_of_model');
$this->name_of_model->inserir($data);
Model:
public function inserir($data)
{
$this->db->insert('***', $data);
if ($this->db->affected_rows() > 0) {
return true;
}
}
I am getting this error when trying to load a .json file into my webpanel/webserver database:
A Database Error Occurred
Error Number: 1054
Unknown column 'priority' in 'field list'
INSERT INTO store_categories (display_name, priority,
description, require_plugin, web_description, web_color)
VALUES ('Hats', 0, 'Cosmetic hats that appear on your head.',
'equipment', NULL, '476291')
Filename:
/usr/www/dynamic/public/server/store-webpanel-1.2.10-hf1/models/categories_model.php
Line Number: 82
Here is the code:
function get_category($id_category)
{
$DB_Main = $this->load->database('default', TRUE);
$DB_Main->where("id", $id_category);
$query_category = $DB_Main->get('store_categories');
if ($query_category->num_rows == 1)
{
return $query_category->row_array();
}
else
{
return array();
}
}
function update_category($post)
{
$DB_Main = $this->load->database('default', TRUE);
$data = array(
'display_name' => $post['display_name'],
'description' => $post['description'],
'require_plugin' => $post['require_plugin'],
'web_description' => $post['web_description'],
'web_color' => $post['web_color'],
'priority' => $post['priority']
);
$DB_Main->where('id', $post['id']);
$DB_Main->update('store_categories', $data);
}
function add_category($display_name, $description, $require_plugin, $web_description, $web_color, $priority=0)
{
$DB_Main = $this->load->database('default', TRUE);
$data = array(
'display_name' => $display_name,
'priority' => $priority,
'description' => $description,
'require_plugin' => $require_plugin,
'web_description' => $web_description,
'web_color' => $web_color
);
$DB_Main->insert('store_categories', $data);
return $DB_Main->insert_id();
}
function remove_category($category_id)
{
$DB_Main = $this->load->database('default', TRUE);
$DB_Main->where('id', $category_id);
$DB_Main->delete('store_categories');
}
}
Anyone know how to fix this?
I doubt this is still relevant to Jack (the original author) almost 2 years later, but if anyone else stumbles across this quite rare web topic as it relates to the TF2 and CSGO Store and the MySQL Web Panel that is used to help administer the in-game Store, the following worked for me and will hopefully help you as well.
I actually just added the priority column into 2 tables as follows:
Using MySQL Workbench open a new SQL script window
Double-click the "store" schema on the left to associate the schema with your SQL script.
Execute the following 2 SQL commands:
alter table store_items add column priority int(11) null;
alter table store_categories add column priority int(11) null;
I am using the CodeIgniter framework. I'm working on the user authentication portion of my website. In my 'users' table of my MySQL database I have a column that I declared as a BOOLEAN (I am aware that it really is a TINYINT(1)) called 'verified' that denotes whether or not a user's email address has been verified. When I try to test the value of this column, my IF statement always evaluates to FALSE, even though I know for a fact the value is 1. Here is a snippet of my code:
public function authenticate_user(){
$pw = hash('sha512', $this->salt1 . $this->input->post('password') . $this->salt2);
$email = $this->input->post('email');
$query = $this->db->get_where('users', ['email' => $email, 'password' => $pw]);
if($query->num_rows() == 1){
$row = $query->row_array();
//die("verified = ".$row['verified']); <-This line shows 'verified = 1' consistently when uncommented.
if($row['verified'] == 1){
$this->session->set_userdata([
'name' => $row['name'],
'email' => $email,
'login_time' => time(),
'last_activity' => time(),
'session_valid' => TRUE
]);
return true;
}
else return 'unverified';
}
else return false;
}
When the credentials are correct, this function always returns 'unverified' and no session variables are set. The function exhibits the correct behavior when the credentials are incorrect. I have confirmed in phpMyAdmin that the column is 1, and I have confirmed that 1 is returned from the database by uncommenting the die() statement above. I have tried using true and '1' (string) in place of the integer 1 and have gotten the same result. Am I doing something wrong? Does CodeIgniter preprocess database returns in a way that would make this not work?
#Sean, your suggestion works. I'm not sure why PHP evaluates it differently than when using the == operator. The way it works is:
if($row['verified'])
Thank you for you help guys.
Try using the empty() function in the if clause:
if(!empty($row['verified'])){
$this->session->set_userdata([
'name' => $row['name'],
'email' => $email,
'login_time' => time(),
'last_activity' => time(),
'session_valid' => TRUE
]);
return true;
}
I have an images table with a column called type. I simply want to update all the rows to change the type to gallery where the user_id matches a particular user.
I am using this code
$this->Image->updateAll(array('Image.type' => 'gallery'),
array('Image.user_id' => $this->Auth->user('id')));
But I get this error: SQL Error: 1054: Unknown column 'gallery' in 'field list'
Why is gallery being added to the field list ?
Isn't the syntax supposed to set type to gallery?
Thanks!
Found this on the manual:
The $fields array accepts SQL expressions. Literal values should be quoted manually.
Thus, the following should work:
$this->Image->updateAll(
array('Image.type' => "'gallery'"),
array('Image.user_id' => $this->Auth->user('id'))
);
In your model do something like this in your method ....
public function saveImage($type='')
{
// I would add a test for $type
$db = $this->getDataSource();
$fields = array('type' => $db->value($type, 'string')); // $db->value() will format strings needed for updateAll()
$condition = array('user_id' => $this->Auth->user('id'));
// I would add a test for user id before running updateAll()
$this->updateAll($fields, $conditions);
}
I'm trying to update a row on my profiles table to reset a users profile picture to the default of user.png. I have the following action in my controller:
public function deleteProfilePicture() {
$this->layout = 'ajax';
// First find the profile ID from the user ID
$profileId = $this->Profile->find('first', array(
'condition' => array('User.id' => $this->Auth->user('id')),
'fields' => array('Profile.id'),
'recursive' => -1
));
$this->Profile->id = $profileId['Profile']['id'];
$this->Profile->saveField('picture', 'user.png', false);
}
However, when I request the URL (/profile/deleteProfilePicture) I get no errors but the database row isn't updated. I have made sure the current profile ID is used by using debug($profileId).
What could be going wrong here?
Edit: The return value of saveField():
array(
'Profile' => array(
'id' => '36',
'modified' => '2013-04-05 14:16:57'
)
)
Try
$this->Profile->id = $profileId['Profile']['id'];
$this->Profile->set(array(
'picture' => 'user.png'
));
$this->Post->save();
I see no error in your code. Try seeing what query is getting executed using this
$log = $this->Model->getDataSource()->getLog(false, false);
debug($log);
based on the result make changes to your query if you find something wrong.
Or try using this
$data['Profile']['id']=$profileId['Profile']['id'];
$data['Profile'['picture']='user.png';
$this->Profile->save($data);
If you set debug to 2 you could see what SQL is being executed, see if your update is actually firing.
Try this
$this->Profile->read(null, $profileId['Profile']['id']);
$this->Profile->saveField('picture', 'user.png', false);
Why are you setting the validation to false? Do you get an error if you omit that?