I have searched all over the internet for information that would help me achieve this seemingly simple thing.
But I can't get my hands on any that is helpful.
What I want to do is to create a custom url link like http://mywebsite.com/users/username,
where
1) 'users' is a MySQL table name
2) 'username' is a column name.
I did some digging on the internet and found this code on github:
<?php
//check for referal links
function referal()
{
$CI =& get_instance();
$cookie_value_set = $CI->input->cookie('_tm_ref', TRUE) ? $CI->input->cookie('_tm_ref', TRUE) : '';
if ($CI->input->get('ref', TRUE) AND $cookie_value_set == '') {
// referred user so set cookie to ref=username
$cookie = array(
'name' => 'ref',
'value' => $CI->input->get('ref', TRUE),
'expire' => '7776000',
);
$CI->input->set_cookie($cookie);
return TRUE;
}elseif ($cookie_value_set == '') {
$cookie = array(
'name' => 'ref',
'value' => 'sso',
'expire' => '15552000',
);
$CI->input->set_cookie($cookie);
return TRUE;
}elseif ($cookie_value_set != '') {
//already referred so ignore
return TRUE;
}else{
return TRUE;
}
}
//end of hooks file
?>
The owner of the gist only mentioned saving the file as referral.php inside the hook folder. This is not helping me with what I want to achieve, I don't know how to use the code:
1. How do I pass the referrer field to the variable username from the users table?
2. How do I load the hook file to view (register.php)?
3. How and where do I call the hook file?
So can anybody give me an insight?
Related
I try to insert my checkbox data in CodeIgniter. but data did not inserted in the database.
here is my view file:
<input type="checkbox" name="feature[]" value="WIFI" >
<input type="checkbox" name="feature[]" value="TV">
I am trying to use implode to convert the array into the string, but then I don't how to add in $data array, so they inserted in together
here is my controller:
public function save()
{
$this->load->model('Partner_model');
$feature = $this->input->post('feature');
$fea=array(
'feature'=>json_encode(implode(",",$feature))
);
$user_data= array(
'pname' => $this->input->post('pname'),
'type' => $this->input->post('type'),
'address' => $this->input->post('address'),
'about' => $this->input->post('about'),
'city' => $this->input->post('city'),
'code' => $this->input->post('code')
);
if($this->Partner_model->save($user_data,$fea))
{
$msg = "save sucesss" ;
}
else
{
$msg = "not save";
}
$this->session->set_flashdata('msg', $msg);
$this->load->view('partner_profile');
}
& here is my model:
public function save($data,$fea)
{
return $this->db->insert('property', $data,$fea);
}
Your model is faulty.
You are passing three arguments to insert() but the third you use is not appropriate.
That argument should be a boolean that indicates whether to escape values and identifiers or not. You need to incorporate $fea into $data which should probably be done in the controller.
There is an easier way to create the array $user_data since it is essentially a copy of $_POST just use $this->input->post().
Also, there is no obvious reason why you use json_encode. Unless you need it that way when you retrieve it from the DB there is no reason to bother with it. Consider removing json_encode.
First, change the model
public function save($data)
{
return $this->db->insert('property', $data);
}
Here's a revised save method
public function save()
{
$this->load->model('Partner_model');
$user_data = $this->input->post(); //makes a copy of $_POST
$feature = $this->input->post('feature');
if($feature) //because $feature will be null if no boxes are checked
{
$user_data['feature'] = json_encode(implode(",", $feature));
}
$msg = $this->Partner_model->save($user_data) ? "save sucesss" : "not save";
$this->session->set_flashdata('msg', $msg);
$this->load->view('partner_profile');
}
An explanation as requested via comments.
A call to $this->input->post('pname') returns the value of $_POST['pname'] if it is exists, but returns null if it does not exist.
When you create $user_data you make six calls to $this->input() with a different "key" each time to make a copy of $_POST.
$this->input->post() without any arguments returns the whole $_POST array. (See documentation)
$user_data = $this->input->post();
Makes a copy of $_POST using one line of code. It will include $_POST['feature'] if any boxes are checked, but $_POST['feature'] will not be set if no boxes are checked.
There are two ways to test if any boxes were checked. First we can test if isset($_POST['feature']) == true or we can test if $this->input->post('feature') == true. I use the second with the call
if($feature)
Which is pretty much the same as any of the following lines
if($feature != false)...
if($feature != null)...
if( ! empty($feature))...
if( ! is_null($feature))...
In other words, if($feature) evaluates as true if $feature is set and is anything except null, false, 0, "0", "" (an empty string), array() (an empty array)
public function save()
{
$this->load->model('Partner_model');
$feature = $this->input->post('feature');
$user_data= array(
'pname' => $this->input->post('pname'),
'type' => $this->input->post('type'),
'address' => $this->input->post('address'),
'about' => $this->input->post('about'),
'city' => $this->input->post('city'),
'code' => $this->input->post('code'),
'feature'=>json_encode(implode(",",$feature))
);
if($this->Partner_model->save($user_data)){
$msg = "save sucesss" ;
}else{
$msg = "not save";
}
$this->session->set_flashdata('msg', $msg);
$this->load->view('partner_profile');
}
model file should be :
public function save($data) {
return $this->db->insert('property', $data);
}
I'm new in laravel. I have a table with menu_id and title I tried to make this title field unique when have the same menu_id. I found the solution here
But I got problem when update it. Can anyone help please?
My code
Validator::extend('unique_custom', function ($attribute, $value, $parameters)
{
// Get the parameters passed to the rule
list($table, $field, $field2, $field2Value) = $parameters;
// Check the table and return true only if there are no entries matching
// both the first field name and the user input value as well as
// the second field name and the second field value
return \DB::table($table)->where($field, $value)->where($field2, $field2Value)->count() == 0;
});
public function updateSubmenu( Request $request) {
$this->validate( $request, [
'menu_id' => 'required',
'title' => 'required|unique_custom:posts,title,menu_id,'.$request->menu_id,
'order_by' => 'required|integer',
'description' => 'required'
],
[
'title.unique_custom' => 'This title already token'
]
);
}
Can you explain what problem have you got on update? Some exception?
Edit:
If you couldn't update record if title not changes, you need to add one condition to Validator:
Validator::extend('unique_custom', function ($attribute, $value, $parameters)
{
// Get the parameters passed to the rule
list($table, $field, $field2, $field2Value) = $parameters;
// If old value not changed, don't check its unique.
$current = \DB::table($table)->where('title')->first();
if( $current->{$field} == $value) {
return true;
}
return \DB::table($table)->where($field, $value)->where($field2, $field2Value)->count() == 0;
});
I am new to CodeIgniter, and am trying to write code to log in after registering using a username and password in registration form using a PHPMyAdmin database. I am not getting anything when I try to log in, and it doesn't display an error or any message.
public function login() {
$this->form_validation->set_rules('username','Username','required');
$this->form_validation->set_rules('password' , 'Password');
if($this->form_validation->run() == TRUE){
//check user in database
$this->db->select('username' , 'password');
$this->db->from('user_register');
$this->db->where(array('username' => $username, 'password' => $password));
$query = $this->db->get();
$user = $query->row();
if($user->email){
$this->session->set_flashdata("Successful login");
$_SESSION['user_logged'] = TRUE;
$_SESSION['username'] = $user->username;
} else {
$this->session->set_flashdata("Error No such record found");
}
}
// load view and showing login form
$this->load->view('login');
}
First, you should read the documentation, looks like you skip that part, but it's very important!
Let's code a little bit and fix the bugs!
User data
Well, users will enter their data and we will check, if evertyhing is correct, we can redirect user to the protected page. You call for variables (see Query:) but you I'm not seeing on your code. You should put like that, before your query job
$username = $this->input->post("username");
$password = $this->input->post("password");
Now, you will be able to use the where to get the user data. =)
Query:
If read about OOP with PHP, you know that when you pass parameters to a method, each parameter have their own "action". In case of the select method, you should keep the data you want to select, on the same quote, because you the way you do, it's like you passing multiple parameters to the method.
$this->db->select('username, password');
$this->db->from('user_register');
$this->db->where(array('username' => $username, 'password' => $password));
First, to decide if the record exist or not, I prefer this way:
if($query->num_rows() > 0) {
$user_data = $query->row();
// We should verify if the user entered the password that correspond to the account.
// If not, we tell them that the password is incorrect.
if($password != $user_data->password) {
$this->session->set_flashdata("error", "Wrong password!");
return redirect(site_url());
}
// You can use the CI built in methods to work with sessions
$this->session->set_userdata(array(
'username' => $user_data->username,
));
$this->session->set_flashdata("success", "You are logged in!");
return redirect(site_url());
} else {
$this->session->set_flashdata("Error: No such record found");
redirect(site_url());
}
Flash data
Yeah, we use flashdata to show a message for the user. But, you should pass an item and the value of this item. Like that:
$this->session->set_flashdata('success', 'Successfully logged in!");
And, to retrieve the data on your views, you can do like...
<?php
$success = $this->session->flashdata("success");
$error = $this->session->flashdata("error");
if(!empty($success)) {
echo $success;
}
if(!empty($success)) {
echo $error;
}
?>
Recommendations
Sessions: https://codeigniter.com/userguide3/libraries/sessions.html
Database: https://www.codeigniter.com/userguide3/database/query_builder.html
Also, I recommed you, to take a minute on YouTube, to understand CodeIgniter.
If I forgot something, let me know! =)
Great Suggestion by webmasterdro's Answer.
I would like to extend it a little bit.
Looking at your code it looks like you have added the query to the controller.
And as a suggestion, if you are using an MVC framework then try to follow some basic MVC flow. because if you are not following that then it will be useless to use a framework.
User Controller to handle the post data and validations.
Use model to do the database query.
Use __construct for loading the common model or libraries.
Do not save plane password use md5 or other encryption technique.
Store User detail to the session which you can use further in after login.
Codeigniter has a great user guide. Try to follow that.
So, your code Should be your like this below.
Controller:
public function __construct() {
parent::__construct();
// Load model
$this->load->model('login_database');
}
public function your_controller_function_name() {
// Check validation for user input in SignUp form
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');
if ($this->form_validation->run() == FALSE) {
$this->load->view('login_form_view');
} else {
$username = $this->input->post("username");
$password = $this->input->post("password");
$result = $this->login_database->registration_insert($username, $password);
//You can do this also if($result != FALSE)
if (!empty($result)) {
// You can set other data to the session also form here
$session_data = array(
'username' => $result['user_name']
);
// Add user data in session
$this->session->set_userdata('logged_in', $session_data);
// You can set flash data here
$this->load->view('your_view');
} else {
$data = array(
'error_message' => 'Invalid Username or Password'
);
$this->load->view('your_login_form_view', $data);
}
}
}
Model:
// Read data using username and password
public function login($username, $password) {
$this->db->select('username');
$this->db->from('user_register');
$this->db->where(array('username' => $username, 'password' => $password));
$query = $this->db->get();
$user_data = $query->row_array();
if ($query->num_rows() == 1) {
return user_data;
} else {
return false;
}
}
I have not added detail related to flash data because the previous answer has explained it properly.
i'm creating an application in symfony 2.8 (with php5.4) and in my form (that i'm building) i want to display a list of a projects through an API in json format.
Now i'm stuck, and i don't know how to do this.
I know the database of the API there is a table "projects" and i want target the column 'name' to display names of projects
here's my code:
/**
* #Route("/form")
*/
public function formAction(Request $request)
{
$url = 'https://website.com/projects.json';
$get_json = file_get_contents($url);
$json = json_decode($get_json);
$form = $this->createFormBuilder()
->add('Project', 'choice') // <-- ???
->add('send', 'submit' ,array('label' => 'Envoyer'))
->getForm();
$form->handleRequest($request);
return $this->render('StatBundle:Default:form.html.twig', array('form' => $form->createView(), 'project' => $json));
}
You can pass the choice as second argument as array as example:
$jsonAsArray = json_decode($get_json, true); // with true return an array
$builder->add('Project', 'choice', array(
'choices' => $jsonAsArray,
// *this line is important, depends of the data*
'choices_as_values' => false,
));
More info in the doc here.
Hope this help
I have a situation where a user uploads his/her trip photos. They are saved in a folder and also supposed to be in database. Situation is: my code is working perfectly on localhost, and many other servers, but not on the server I want. Though it uploads files successfully, but the query is not executed which is supposed to save file path in database. I am stuck in this problem from more than a week. The same code works in other places. Here is my controller:
public function trip_photos(){
$this->load->model('UserModel');
$this->load->model('CommentModel');
$this->load->library('session');
print_r($_FILES);
$logged_session = $this->session->userdata('login');
if($logged_session == 1) {
$this->load->model('TripModel');
$this->load->model('UserActivityModel');
$uid = $this->session->userdata('uid');
$tid = $this->input->post('tid');
foreach($_FILES as $key => $image_upload){
$upload = self::upload_trip_photo($key);
if($upload['status']){
$this->TripModel->add_trip_photo($uid, $tid, $upload['file']);
}
}
$this->UserctivityModel->add_user_photo($uid, $tid);
}else{
redirect('/');
}
}
private function upload_trip_photo($image){
$msg = '';
$config['upload_path'] = './assets/images/trip/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 2048;
$config['file_name'] = parent::getGUID();
$this->load->library('upload', $config);
if ($this->upload->do_upload($image))
{
$data = $this->upload->data();
$resize['image_library'] = 'gd2';
$resize['source_image'] = "./assets/images/trip/" . $data['file_name'];
$resize['create_thumb'] = TRUE;
$resize['maintain_ratio'] = TRUE;
$resize['width'] = 222;
$resize['thumb_marker'] = '';
$resize['new_image'] = "./assets/images/trip/thumbnails/" . $data['file_name'];
$this->image_lib->resize();
$this->image_lib->clear();
$this->image_lib->initialize($resize);
if($this->image_lib->resize()){
$status = true;
$msg = $data['file_name'];
}else{
$status = false;
}
}
else
{
$status = false;
}
#unlink($_FILES[$image]);
return array('status' => $status, 'file' => $msg);
}
when I enabled CI_Profiler, it says that only 2 out of 3 query executed on the server I want it to work. But the same profiler suggests that 3 of 3 queries executed on localhost or other servers. Its so confusing.
Please note that I already have checked the following:
File Upload: On
upload_raw_post_data: On
selinux permissions: disables (mine is centos)
File permissions: 777
php memory_limit: 128 MB
max_size: 8 MB
var_dump, print_r, echo all not working or displaying any information from controller.
somehow, this in above code: $upload = self::upload_trip_photo($key); is not giving it back the file path it requires. Can anybody help please? #DFriend
UPDATED Turns out that in the localhost are other servers where its working, this array is returned by the function upload_trip_photo to the $upload variable:
Array ( [image0] => Array ( [name] => maintour3.jpg [type] => image/jpeg
[tmp_name] => D:\xampp\tmp\php2539.tmp [error] => 0 [size] => 200491 ) )
array(2) { ["status"]=> bool(true) ["file"]=> string(36)
"E3965DFC8B265CEFF522A1EC43B33E34.jpg" }
while in the server where its not working, only this array is returned:
Array ( [image0] => Array ( [name] => mg7.jpg [type] => image/jpeg
[tmp_name] => /tmp/phpNcCnX0 [error] => 0 [size] => 28460 ) )
It means this statement in the upload_trip_photo() function:
return array('status' => $status, 'file' => $msg);
is not returning the requested array, with file name and status. And why? I am totally clueless.
Help Please!
Thankfully this worked after extensive debugging. The line
if($this->image_lib->resize()){
$status = true;
$msg = $data['file_name'];
}else{
$status = false;
}
was not working. Later when I set it to display_error() method, it showed that my server did not support GD library. This is an essential library to manipulate Graphics. So, the query was not being executed, as the $status variable was set to false.
I recompiled my php with GD Library module. And bigno! its working now.
Thanks for staying with me. :)