setting user session in laravel by user_name or user_id - html

I want to set user session in laravel, same as we can do it in core php using following code
<?php session_start();
if(!isset($_SESSION["user_name"]))
{ header("Location:index.php?msg=Please log in");
}else{
$sql="UPDATE users SET log_time = '".date('Y-m-d H:i:s')."'
WHERE id=".$_SESSION['id'];
$res = mysql_query($sql);
}
?>
I want to make session in laravel either by user_id or by user_name.

Laravel provides direct support for Session using its Session class
use Session; // at top of class
if (!Session::has('user_id'))
{
return Redirect::to('index.php?msg=Please log in');
}
else
{
$sql="UPDATE users SET log_time = '".date('Y-m-d H:i:s')."'
WHERE id=".Session::get('user_id');
$res = mysql_query($sql);
}
EDIT:
also laravel provides support for Eloquent model so do not write queires like that, just follow this structure
$user = User::find(Session::get('user_id'));
$user->log_time = date('Y-m-d H:i:s');
$user->update();

Related

How to automatically edit MySQL databases in Cpanel

I'm attempting to make a login system, and am hosting it on a web server using Namecheap. I decided to use the Cpanel MySQL Databases to save the login values (username, password, etc.), however, I haven't been able to add values to the MySQL databases. I can easily manually add to the databases, but how do I add using code (preferably python, but any language works as well).
I don't have any previous attempts because I haven't found anything showing how to do this.
I found a solution using php, which works just as well as it would in python.
<?php
$username = $_POST['username'];
$password = $_POST['password'];
$servername = "localhost";
$server_username = "animfqrw_loginUsername";
$server_password = "loginPassword";
$dbname = "animfqrw_userLogin";
$userID = 1;
//Connects to the mysql database
$conn = new mysqli($servername, $server_username, $server_password, $dbname);
//Ends php code if php fails to connect to mysql database
if ($conn->connect_error) {
die("Error");
break;
}
//Finds the last User_ID
$sql = "SELECT User_ID FROM Users ORDER BY User_ID DESC LIMIT 1;";
$result = $conn->query($sql);
//Fetches the last User ID so that the User ID's are all in order
while($row = $result->fetch_assoc()) {
$userID = $row["User_ID"] + 1;
}
//Add's the row to the mysql database
$sql = "INSERT INTO Users (User_ID, Username, Password)
VALUES ($userID, '$username', '$password')";
$conn->query($sql);
?>

What's the best way to fetch an array

Alright, so I believe that there is a better way that I can fetch an array from the database, here's the code right now that I have.
$id = 1;
$userquery = mysql_query("SELECT * FROM login WHERE id='$id'");
while($row = mysql_fetch_array($userquery, MYSQL_ASSOC)) {
$username = $row['username'];
$password = $row['password'];
$email = $row['email'];
}
So If I am not wrong, you want a better way to get all the returned rows from mysql in a single statement, instead of using the while loop.
If thats the case, then I must say mysql_ drivers do not provide any such functionality, which means that you have to manually loop through them using foreach or while.
BUT, since mysql_ is already depricated, you are in luck! you can actually switch to a much better and newer mysqli_ or the PDO drivers, both of which DO actually have functions to get all the returned rows.
For mysqli_: mysqli_result::fetch_all
For PDO : PDOStatement::fetchAll
Eg.
mysqli_fetch_all($result,MYSQLI_ASSOC);
// The second argument defines what type of array should be produced
// by the function. `MYSQLI_ASSOC`,`MYSQLI_NUM`,`MYSQLI_BOTH`.
Like the comments already told you: PHP's mysql driver is deprecated. And you should use prepared statements and parameters.
for example in PDO your code would look something like this:
//connection string:
$pdo= new PDO('mysql:host=localhost;dbname=my_db', 'my_user', 'my_password');
//don't emulate prepares, we want "real" ones:
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
//use exception-mode if you want to use exception-handling:
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$id = 1;
//it's always better to strictly use backticks for db-names (db, tables, fields):
$sql = "SELECT * FROM `login` WHERE `id` = :id";
try
{
//create your prepared statement:
$stmt = $pdo->prepare($sql);
//bind a parameter and explicitly use a parameter of the type integer (in this case):
$stmt->bindParam(":id", $id, PDO::PARAM_INT);
//execute the query
$stmt->execute();
}
catch(PDOException $e)
{
exit("PDO Exception caught: " . $e->getMessage());
}
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$username = $row['username'];
$password = $row['password'];
$email = $row['email'];
}
here you go: your PHP-MySQL routine is save against SQL-injections now and no longer uses deprecated PHP-functions! it's kinda state of the art ;)

Get only personal record of the DB and not all of the records

When you log in on my site, you'll directly be directed to your profiles page. So that you can see your name, phone, email, etc. But at the moment when I log in on my site, I get directed to my profile page but I get all data for every user in my DB. So I'm getting the name of every user, the phone of every user, etc. I only want to get the data of the person who logged in. How can I achieve this?
I did some thinking about it, and came up with doing a where userID = ID of the user HERE
But I don't know where I'll be able to get the ID of this user. When logging in I'm starting a session, so would I need to store the logged in users ID in the session? Or isn't that secure?
I'm learning and working with CodeIgniter, so I'm doing it in a MVC pattern.
Controller where I login and set my session
if($query){
$data = array(
'username' => $this->input->post('loginEmail'),
'is_logged_in' => true
);
$this->session->set_userdata($data);
Controller
if($logged_in){
//if the user is logged in
$this->load->model('profile_model');
if($query = $this->profile_model->userInfo()){
$data['records'] = $query;
$data['content'] = 'profile_view';
$this->load->view('templates/template', $data);
}
}
Model
class Profile_model extends CI_Model{
function userInfo(){
$query = $this->db->get('tbl_users');
return $query->result();
}
}
View where my I want to show my data
if(isset($records)){
foreach($records as $row){
echo $row->username;
echo $row->cellphone;
}
}
All you are missing is a WHERE statement in your model. As an argument for the WHERE statement you can use your session variable containing your email address(assuming your database table stores emails in a field called 'username':
class Profile_model extends CI_Model{
function userInfo(){
$this->db->where('username', $this->session->userdata('username'));
$query = $this->db->get('tbl_users');
return $query->result();
}
}
Or you can pass the email/username to the model from the controller:
if($logged_in){
//if the user is logged in
$this->load->model('profile_model');
$username = $this->session->userdata('username');
if($query = $this->profile_model->userInfo($username)){
$data['records'] = $query;
$data['content'] = 'profile_view';
$this->load->view('templates/template', $data);
}
}
and then in your model:
class Profile_model extends CI_Model{
function userInfo($username){
$this->db->where('username', $username);
$query = $this->db->get('tbl_users');
return $query->result();
}
}
I don't know what your columns are named in your database, or I could be more precise.
If usernames in the database are different from email addresses, change the line in the model to:
$this->db->where('email', $username);
Hope this helps!

Return id from combined functions

I'm trying to optimize a platform I created, and removing code that maybe aren't necessary. and since I started read about PHP classes and decided to rewrite the entire function page.
I'm having two functions for my login page.
valid_credientials($email,$password){} and
function fetch_user_id($email){ }
the fetch_user_id returns the id from logged in user, so my session would change from session email to session uid.
Now Am i trying to combine this two function, but i get only error messages so i was thinking, that maybe i need this two function ?
This is what i have for now.
public function valid_credientials($email,$password){
if(!empty($email) && !empty($password)){
$query = $this->db->prepare("SELECT id FROM user WHERE email=? AND password=?" );
$query-> bindParam(1, $email);
$query-> bindParam(2, $password);
$query-> execute();
if($query->rowCount() == 1){
$row = $query->fetch(PDO::FETCH_ASSOC);
return $row[id];
echo "user verified Access granted";
}
}else{
echo 'Wrong Username of password';}
}
}
function fetch_user_id($email){
global $db;
$query = $db->query("SELECT id FROM user WHERE email='{$_SESSION['email']}'");
$row = $query->fetch(PDO::FETCH_ASSOC);
return $row[id];
}
As you see am i trying to use the $row = query inside the valid_credential function.
but it only returns error - undefined constant id - assumed 'id' in.
thanks!

use a single return from a sql query

I'm using PHP to make a very specific sql query. For example sake, I have the user's ID number, but I need their name. So I do a sql query from that table with the ID number in order to return the name.
$result = mysql_query("SELECT name FROM users WHERE userID=$thisuserid",$db);
Now I want to use that. What's the most succinct way to go about making that result into a variable ths I can use?
edit:
I'm hoping that this is not the answer:
$rowCheck = mysql_num_rows($result);
if ($rowCheck > '0') {
while ($row = mysql_fetch_assoc($result)){
foreach ($row as $val){
$username = $val;
}
}
}
I have used something like this to keep it short in the past:
list($name) = mysql_fetch_row(mysql_query("SELECT name FROM users WHERE userID=$thisuserid",$db));
echo $name;
In my opinion, the best way to fetch any SQL result is through mysql_fetch_assoc(). To use it, you would do something like this:
$result = mysql_query("SELECT name FROM users WHERE userID=$thisuserid",$db);
while ($row = mysql_fetch_assoc($result)) {
echo $row['name']; // You get an array with each column returned from your query.
}
Still, MySQL extension has been replaced for MySQLi, which is acknowledged to be faster and more practical. It has both OOP and structural bindings, and takes more into account your server settings.
$result = mysql_query("SELECT name FROM users WHERE userID=$thisuserid",$db);
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$name = mysql_fetch_row($result)[0];
You should use MySQLi as bellow:
$db = new MySQLi($host,$user,$pass,$db);
$query = $db->query('SELECT name FROM users WHERE userID='.$thisuserid);
$result = $query->fetch_object();
echo $result->name;
If you use SELECT * so you also can access via $result->{field_name}