I have 3 login fields (name, pass, company id). Now when user clicks "Log me in" button CI should select and work with database according to company id (and check user in this database and when he is logged in, work with this database over whole session /each company has its own database/).
How can I do this?
I found this but it looks like it is not the right solution.
Many thanks
CodeIgniter: Connection to your Database
Maybe the link above will help you out.
You have to set a new db connection for the specific company. In CodeIgniter it is really simple.
Combine it with THIS PROBLEM to get access to the database settings setted in the database-config.
Example:
<?php
$config = array();
$config['hostname'] = $this->db->hostname;
$config['username'] = $this->db->username;
$config['password'] = $this->db->password;
$config['database'] = 'companydb';
$config['dbdriver'] = $this->db->dbdriver;
$companydb = $this->load->database($config);
$companydb->query('SELECT ... FROM ... WHERE ...');
?>
Related
I am making an application using laravel and twilio that gets feedback about student performance. The logic as follows.
A user, in my case the Student(called resident) logs in and uses a
web page form to send an eval request to a teacher (called
attending). This step starts a session and saves teacher info and
student info.
A random question is picked from a database and saved to the session.
The phone number of the teacher is pulled from a database and the random question is pulled from session and sent to the teacher on SMS using twilio.
The teacher responds with yes, no, or DNS (did not see) via Twilio SMS.
The teacher's response along with the student name, the teacher name and the question asked are saved to a database.
My application works up until step 5. The problem is that a new session is being started when the teacher responds via SMS. So everything after the response is saved to a new session. I can't get access to the original session. I think I need a way to automatically grant the teacher access to the student(ie. user's account). This seems to be a problem with it being a 3rd party application. Can this be done or is there another way to accomplish this?
Below is the code I am using for the response. It is not able to access the session that contains the residentName, the firstQuestion, or the attending_name data. It puts null for those values and uploads null to the database. How do I get access to the initial session in this situation?
namespace App\Http\Controllers;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Session;
use Twilio\Rest\Client;
use Twilio\Twiml;
use App\Question;
use App\Answer;
class AskFirstQuestionsController extends Controller
{
public function qOneResponse(Request $request) {
$responderNumber = $request->input('From');
session()->put('responderNumber', $responderNumber);
session()->save();
$responderAnswer = strtolower($request->input('Body'));
$residentName = session::get('residentName');
$firstQuestion = session::get('first_question');
$attending_name = session::get('attending_name');
if (strpos($responderAnswer, 'yes') !== false) {
$answer = new
Answer(['attending'=>$attending_name,'resident_name'=>$residentName,'question_body'
=>$firstQuestion, 'answer_yes'=>1]);
$answer->save();
$smsResponse = "Great! Please help us reinforce this action by providing specific feedback
to the resident about what they did. Thank You for teaching!";
} else if (strpos($responderAnswer, 'no') !== false) {
$answer = new
answer::create(['attending'=>$attending_name,'resident_name'=>$resident_name,'question_body'
=>$firstQuestion, 'answer_no'=>1]);
$answer->save();
$smsResponse = "Ugh, ok...we will work on this. If you feel comfortable, please help us by
providing specific feedback to the resident about what they need to work on. Thank You for
teaching!";
} else if (strpos($responderAnswer, 'dns') !== false) {
$answer = new
answer::create(['attending'=>$attending_name,'resident_name'=>$resident_name,'question_body'
=>$firstQuestion, 'answer_dns'=>1]);
$answer->save();
$smsResponse = "How about trying a different question?";
} else {
$smsResponse = 'Please answer yes, no or dns.';
}
return response($this->respond($smsResponse))->header('Content-Type', 'application/xml');
}
public function respond($smsResponse) {
//get responderNumber and use it below
$responderNumber = session::get('responderNumber');
$response = new Twiml();
$response->message($smsResponse, ['to' => $responderNumber]);
return $response;
}
Do I need to do some type of multiauth approach and somehow grant the teacher automatic access to the student's account (user account)? Or do I have to re-write the logic so that the response-request lifecycle closes and then try to write to the database (maybe it will then use the original session data?)? Or is there a simpler way? Please help. I have been stuck for more than a week.
Twilio developer evangelist here.
I'm not a Laravel developer, but session objects in web application frameworks like this are normally tied to a cookie that either stores the contents of the session or an ID for the session which points to the contents in a database in order to add state to a user's session within a browser.
When Twilio receives an incoming SMS message the webhook that is sent to your server is not connected to the browser session that the user is part of, so you cannot access the same data.
Instead of using the session, you should store this as part of your actual database so that you can look up the details from the database when you receive the SMS.
I have integrated redis cache driver in laravel. My app is social and music. So the authenticated user can access the app, I have to cache the data based on the logged in user. How can I implement this? Can anyone please help out?
Here is the code that I am using right now. Below is the code that fetches the logged in user's posts based on user id. In the code below, I am creating a cache tag tfeedsposts that will set the post data if the cache is not already set.
Is it the best practice to use the same cache tag for every logged in user?
Because I am thinking the same tag will not work for every logged in user, as the user will have different data, so storing the data in the same cache tag will not show the actual data to the user.
If there is an effective way to achieve this, then please let me know.
$cachename = 'tfeeds-offset:'.$this->offset.'-limit:'.$this->limit;
$cached = Cache::tags(['tfeedsposts'])->has($cachename);
if ($cached) {
$posts = Cache::tags(['tfeedsposts'])->get($cachename);
} else {
$posts = Post::whereRaw("visibility_id = 1 and user_id IN($friendsids_string) or visibility_id = 2 and user_id IN($follwingids_string) or visibility_id = 3 and user_id IN($follwingids_string) or visibility_id = 3 and user_id IN($friendsids_string)")->orWhere('user_id', $id)->with(['users_liked','users_viewed','shares', 'user','parentpost', 'comments','comments.user', 'comments.comments_liked', 'comments.replies', 'comments.replies.user', 'comments.replies.comments_liked','users_tagged' , 'notifications_user'])->latest()->paginate(Setting::get('items_page'));
Cache::tags(['tfeedsposts'])->put($cachename, $posts, $this->cachettl);
}
i have start a new application html5 and i need to send from that app the info user_points to the database i have the code that send a fixed amount points.
But Now I need to change the php code to receive ajax request to update is points on database From My html5 app.
what i can change to this php code to receive the ajax variable user_points and store in database?
<?php
session_start();
include_once 'dbconnect.php';
if(!isset($_SESSION['user']))
{
header("Location: index.php");
}
$res=mysql_query("SELECT * FROM users WHERE user_id=".$_SESSION['user']);
$userRow=mysql_fetch_array($res);
// Retrieve data from database
$result=mysql_query($sql);
//$sql = mysql_query("UPDATE `users` SET points=`points`+5 WHERE user_id='".$_SESSION['user']."'");
$user_id = mysql_real_escape_string($_SESSION['user']);
$sql = mysql_query("UPDATE `users` SET user_points = user_points +'user_points' WHERE user_id = " . $_SESSION['user']);
// close MySQL connection
mysql_close();
?>
assume your php script is called run.php
and assume run.php is called via ajax like this http://yourserver/run.php?user_points=10&userid=12&sessiontan=8162836zqwizß182402834080oio
your script run.php would need to look like this:
<?php
session_start();
include_once 'dbconnect.php';
if(isset($_GET['userid']) and isset($_GET['user_points'] and isset($_GET['sessionpin']))) {
$res=mysql_query("SELECT userid FROM sessiontans WHERE user_id=x".dechex($_GET['userid'])" and sessiontan=x".dechex($_GET['sessiontan']));
if($row = mysql_fetch_array($res)) {
$sql = mysql_query("UPDATE `users` SET user_points = user_points + x".dechex($_GET['user_points'])." WHERE user_id = x" . dechex($_GET['userid']));
}
}
// close MySQL connection
mysql_close();
?>
As far as I am aware the session context is not available in ajax called scripts. So security wise that needs to 'simulated' via sessiontans or similar mechanisms. I assumed now, you would follow a sessiontan approach. A session tan be created in your app as soon as the user logs and is via time stamps only valid for a tiny time frame (a couple of minutes/hours). A sessiontan would need to be different from session-IDs.
I personally would add more sophisticated checks on the user-points to make sure that the those are not tricked... Anyway that is more on the 'game logic' side and would require a lot more insight on what this is all about.
Also in terms of performance tuning both statements could become part of a multi query: http://php.net/manual/de/mysqli.multi-query.php
Again this is advanced programming tactics and superexceeds the scope of your question.
I have a database and a user which is created through cpanel(i have added that user to that database and i am able to access that database using that user and its password. i have given all privileges to that user through cPanel(by clicking on the username in 'current database' table in cpanel and clicking on all privileges check box ).
In my application(which is created using PHP- Codeigniter framework) i want to create new database and tables in that database as per users requirement. For that i am using Codeigniter dbforge class for creating database and the tables in that.
$this->load->dbforge();
if ($this->dbforge->create_database($database_name)){
$config['hostname'] = "localhost";
$config['username'] = "user_name";
$config['password'] = "users_password";
$config['database'] = $database_name;
$config['dbdriver'] = "mysql";
$config['dbprefix'] = "";
$config['pconnect'] = TRUE;
$config['db_debug'] = TRUE;
$config['cache_on'] = FALSE;
$config['cachedir'] = "";
$config['char_set'] = "utf8";
$config['dbcollat'] = "utf8_general_ci";
$config['swap_pre'] = '';
$config['autoinit'] = TRUE;
$config['stricton'] = FALSE;
$db_new=$this->load->database($config,TRUE);
$this->db=$db_new;
$this->load->dbforge();
$fields=array(
'id'=>array('type'=>'INT','auto_increment'=>TRUE,'constraint'=>'5'),
'first_name'=>array('type'=>'VARCHAR','constraint'=>'60'),
'last_name'=>array('type'=>'VARCHAR','constraint'=>'60','null' => TRUE),
);
$this->dbforge->add_field($fields);
$this->dbforge->add_key('id',TRUE);
$this->dbforge->create_table('clients');
}
In the above code i am creating a database first and then loading that database as the current database . This code works perfectly in local host WAMP server but when i uploaded it to the server and then tried to create the database it gives the following Error
Error No 1044: Access denied for user 'username'#'localhost' to database 'database_name'
The line of code which caused thr error is
if ($this->dbforge->create_database($database_name)){
*In that database config setting shown in the above code the 'username' and 'password' is given as the username and password of the already existing database(which is created through cPanel) . Is that the problem...?* .
the current user using which we are trying to create new database is having all the avilable privileges. but in that 'CREATE DATABASE ' privilege is not there.
For database naming I have used the ' prefix_ ' in the database name(CPanel database naming format)
How can i create the database using dbforge class and access to that database using a existing user ...?
Try Create a Super User first
mysql > GRANT ALL PRIVILEGES on databasename.* TO "username"#"localhost" IDENTIFIED BY "password";
I have a multi-tenancy application that I am developing and I'm nearly there.
Currently I am using one database per customer - copying it each time and naming depending based on $_SERVER['http_host']...
A lot of the tables each database never change, and contain the same information.
I would like to have a main application database that contains this information, including a list of clients and what there database is called. This database would then be used to select the correct customers database...
Is this possible and can anyone point me in the direction of a suitable tutorial?
Thanks
OK, so you'll need different database configs for your "administrative" database and your "customer" databases.
Use the examples from this page to generate those separate configs:
http://ellislab.com/codeigniter/user_guide/database/configuration.html
Then, in your main controller (please tell me your extending a MY_Controller.php and not just using CI_Controller.php), you'll want to read your 'admin' database and get all client information. You'll then want to generate a $config array for this client database and reload the database with the new $config array:
// in MY_Controller constructor
// do your thing here to connect to the admin database and get client details
// ...
//
$config['hostname'] = "localhost";
$config['username'] = $client_db_username; // you got this from the 'admin' database
$config['password'] = $client_db_password; // you got this from the 'admin' database
$config['database'] = $client_db_name; // you got this from the 'admin' database
$config['dbdriver'] = "mysql";
$config['dbprefix'] = "";
$config['pconnect'] = FALSE;
$config['db_debug'] = TRUE;
$config['cache_on'] = FALSE;
$config['cachedir'] = "";
$config['char_set'] = "utf8";
$config['dbcollat'] = "utf8_general_ci";
$this->load->database($config);
You'll then have a connection to the client database.
Note
If you'll need to connect to both databases back and forth, then you can connect to multiple databases as explained on this page: http://ellislab.com/codeigniter/user_guide/database/connecting.html