Return id from combined functions - mysql

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!

Related

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 ;)

setting user session in laravel by user_name or user_id

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();

Function returns 1 instead of result (PDO)

I have a function which is printed below. THis is meant to dynamicly draw user data from the database using PDO (that situation is clear and all works well). But, instead of returning the result (i e. an email for you("email)), it returns the number 1.
Here's my setup:
public function you($row) {
if(isset($_COOKIE["SK"])) {
$pw = $this->baseXencode($_SESSION["password"]);
$usr = $this->baseXencode($_SESSION["username"]);
$q = "SELECT $row FROM SN_users WHERE username=':USR' AND password=':PW'";
$this->netCore->q($q);
$this->netCore->bind(":PW", $pw);
$this->netCore->bind(":USR", $usr);
$result = $this->netCore->single();
$result = $result[$row];
return $result;
} else {
$q = "SELECT $row FROM SN_users WHERE username='Anonymous' AND password='Anonymous'";
$this->netCore->q($q);
$result = $this->netCore->single();
$result = $result[$row];
return $result;
}
}
}
$this->netCore->q() = PDO query
$this->netCore->single() PDO fetch(PDO::FETCH_ASSOC)
As for ->bind, self-explanatory.
Please help, will be very much appreciated.^^
When using parametrized queries, you don't put the parameters in quotes. That prevents the parameters from being substituted, since it's treated as a literal string. So it should be:
$q = "SELECT $row FROM SN_users WHERE username=:USR AND password=:PW";
I'm surprised it's returning 1. I'd expect your code to cause an error, because single() should be returning false, and false[$row] is not valid.
You should also check that a row was returned; if the username and password are not valid, you won't get an result. So it should be:
$result = $this->netCore->single();
if ($result) {
return $result[$row];
} else {
return false;
}
And the caller of you() needs to check the value as well.

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!

MySQL "commands out of sync" appears when migrating to stored procedures

I have some working php/mysql which I am now migrating to stored procedures.
As soon as any stored procedure is called, subsequent CALLs and SELECTs fail with "Commands out of sync; you can't run this command now".
Existing stored procedures which are not SELECTs work fine.
function db_all ($query)
{
log_sql_read ($query);
$result = mysql_query ($query, db_connection ());
if (!$result)
{
log_sql_error ($query);
return Array ();
}
$rows = Array ();
while ($row = mysql_fetch_assoc ($result))
array_push ($rows, $row);
mysql_free_result ($result);
return $rows;
}
db_all ("SELECT 1 as `test`");
db_all ("SELECT 2 as `test`");
db_all ("CALL `$db`.`select_info`($id);"); // RETURNS CORRECT DATA
db_all ("CALL `$db`.`select_info`($id);"); // ERROR HERE
db_all ("SELECT 5 as `test`"); // ERROR HERE
This error is explained elsewhere as a result of not calling mysql_free_result, but I do call this. So what's wrong?
I'm seeing some solutions which refer to mysqli. I need a non-mysqli solution for now.
The problem is when executed, a stored procedure will give you two resultsets back. One with the actual resultset and another with the status of the executing. And you need to consume both before making another call that returns result set.
In mysqli_* you can utilize mysqli_multi_query, mysqli_store_result, mysqli_next_result to achieve that. You can see how to do that in mysqlihere.
In your case with mysql_* you can just close the connection after you done fetching results.
function db_all ($query)
{
$link = db_connection(); //Open connection
log_sql_read ($query);
$result = mysql_query ($query, $link);
if (!$result)
{
log_sql_error ($query);
return Array ();
}
$rows = Array ();
while ($row = mysql_fetch_assoc ($result))
array_push ($rows, $row);
mysql_free_result ($result);
mysql_close($link); //Close the connection
return $rows;
}