PHP, MYSQL workbench, postman not working correctly - php

I have 2 users in a table, for example Vesna and Silvija, Vesna is first, Silvija second and if I type Silvija in postman he will return me "User does not exist and than Id of a user Silvija. This should be working on a way that Postman return just an Id of a User and if I type user that doesnt exist he should return that user doesnt exist. But when I type a users that doesnt actually exist he will return 2 times that users doesnt exist instead one time because table have 2 users that doesnt match entered user. Hope I have explained it understandably and that someone can help me.
foreach($oUsers as $oUser)
{
if($oUser->USERNAME == $sUsername)
{
$_SESSION['user_id'] = $oUser->USER_ID;
$_SESSION['username'] = $oUser->USERNAME;
echo $_SESSION['user_id'];
break;
}
else
{
echo ' User does not exist';
}
}

You can not use echo '...' inside the foreach loop because echo is executed in every iteration.
$found = false;
foreach($oUsers as $oUser){
if($oUser->USERNAME == $sUsername){
$_SESSION['user_id'] = $oUser->USER_ID;
$_SESSION['username'] = $oUser->USERNAME;
$found = true;
break;
}
}
if($found === true){
echo $_SESSION['user_id'];
}else{
echo ' User does not exist';
}

Related

How to retrieve all rows from a database table and loop through each row to match password PHP

i need to pull all the rows from the database table and loop through each of them to find a row that matches both the Msisdn and Password? please help guys...
$state = $this->conn->prepare($sql);
$state->execute();
$userRow = $state->fetchAll();
foreach($userRow as $dataObj) {
if($userData['msisdn'] === $dataObj['Msisdn']) {
if($userData['userpass'] === $dataObj['Password']) {
$_SESSION['user_id'] = $dataObj['id'];
if($_SESSION['user_id'] == true) {
echo "You're logged in...";
} else {
return false;
}
} else {
echo "<font color='red'>" . "{$error} <b>Incorrect PIN</b>. Please enter again, you have <b>2 attempts</b> remaining." . "</font><br><br>";
echo "<font color='slateGrey'>contact us on <a>086 000 3344</a> to register or request a </font><a target='_blank' href='support#example.co.za'>callback.</a>";
return false;
exit();
}
} else {
echo "<font color='red'>" . "{$error} User not found... Please contact your service provider..." . "</font><br><br>";
echo "<font color='slateGrey'>either call on <a>086 000 3344</a> or request</font> <a href='support#example.co.za'>callback.</a>";
return false;
exit();
}
return false;
}
The whole point of using a database is that you don't have to do this! That's why an RDBMS provides a WHERE clause to the SELECT statement. If you have indexed your table properly, the RDBMS only needs to look up a few rows to find the matching entry (if available). So you don't have to write all this code. Yourself.
$password = hashing_fuciont($dataObj['Password']); /* you are hashing the password aren't you? */
$stmt = $state->prepare("SELECT * FROM users where username=? password=?")
$stmt->execute( array("username"=>$username, "password"=>$password));
$userRow = $state->fetchAll();

Only one user can open admin.ctp file

I want to do a page, and this page can open only one user. I want to do something like this: If user id = 1 then its opening else its throwing error.
I already tried this :
if (in_array($this->action, array('controller' => 'users', 'action' => 'admin'))) {
$postId = (int) $this->request->params['pass'][0];
if ($this->User->isOwnedBy($postId, $users['id'] = 1)) {
return true;
}else{echo "You are not admin!";}
}
Then I thinked, maybe this is a little bit easier ?
public function admin($id = null) {
$this->User->id = $id;
if ($id == 1) {
echo 'You are admin';
}
else {
throw new NotFoundException(__('You are not admin !'));
}
}
But its not working, How I get this user id in to this if. This second solution throwing only this error, but I dont want it, I want access if user id is 1.
Here is users picture
Thank you for any clue or solution.
Try this-
public function admin($id = null) {
$currentUserId = $this->Auth->user(id);
//$isAdmin = $this->User->hasAny(
//array('User.id' => $currentUserId)
//);
//if ($isAdmin) {
if ($currentUserId == 1)
echo 'You are admin';
} else {
throw new NotFoundException(__('You are not admin !'));
}
}
For logged in users.
The recommended approach for getting logged in user data is via the AuthComponent itself:
// in any controller
$userId = $this->Auth->user('id');
See Accessing the logged in userAccessing the logged in user in the Auth section of the CakePHP Book.
Better Option:-
use role id for admins, this will help you for multiple admins. and give negative id to admin:-
like add role_id column in user table and give value to -1
public function admin($id = null) {
$role = $this->Session->read('Auth.User.role_id');
if ($role < 0)
echo 'You are admin';
} else {
throw new NotFoundException(__('You are not admin !'));
}
}
so you want to check if the user ID is 1 ??
//Fetch the user informations from database and stock it into $user
if(is_admin($user[id])){
echo 'You are admin';
}
else{
echo 'You are not admin';
}
function is_admin($id = NULL){
if($id == 1){
return true;
}
else{
return false;
}
}
tell me if I misunderstood
Edit :
According to our chat, try this :
//Fetch the ID of the user and stock it in $user_id
if($user_id == 1){
echo 'You are admin';
}
else{
echo 'You are not admin';
}

Codeigniter 2.2 failed create session

I use CI 2.2 to build a simple login system. But I get problem when I try to generate session. Of course I have properly set up libraries (database, session) and User_M. When I retrieve data from database (without session), that's work fine. This is my Controller code:
public function verify()
{
// Define variable
$user = $this->input->post('username');
$pass = $this->input->post('password');
// Check input data
if (!empty($user) AND !empty($pass))
{
// Check match data from db
$checks = $this->User_M->check_user($user, $pass);
if($checks->num_rows() == 1)
{
foreach ($checks->result() as $check)
{
$sess = array (
'username' => $check->username,
'logged_in' => TRUE
);
$rest = $this->session->set_userdata($sess);
if ($rest)
{
echo "working";
} else {
echo "not working";
}
}
} else {
echo "Not found";
}
} else {
echo "You've empty field";
}
}
Additional explain, I check the result with if ($rest)...bla..bla..bla, that's echoing Not Working. Please let me know where's my mistakes?
Thank in advance
I think the problem is with this statement
$rest = $this->session->set_userdata($sess);
the set_userdata() does not return anything, so according to your condition it will always execute the else part.
Try to change your condition like this
if (!empty($this->session->userdata("username"))){
echo "Working";
}else{
echo "Not Working";
}

Admin and User log in from two different tables

I was wondering if anyone could help me - I have successfully created a log in system allowing a user (student) to log in. My system also requires an admin log in, with the admin having privileges to view pages that the student does not. Both the admin and student information comes from two different tables. Below is the code I have used for the student log in (there are two different pages - users and login). I am stuck as to how to implement the admin log in. Any help is appreciated!
(Admin will log in using 'adminnum' and 'adminpassword'.
login.php
<?php
include "core/init.php";
include "includes/content.php";
if (empty($_POST) === false) {
$studentemail = $_POST ['studentemail'];
$studentpassword = $_POST ['studentpassword'];
if (empty($studentemail) === true || empty($studentpassword) === true) {
$errors[] = "You need to enter an email address and password";
} else if (user_exists($studentemail) === false) {
$errors[] = "We can't find that email address. Have you registered?";
} else {
if (strlen($studentpassword) > 32) {
$errors[] = 'Password too long';
}
$login = login($studentemail, $studentpassword);
if ($login === false) {
$errors[] = 'That email/password combination is incorrect';
} else {
$_SESSION['studentid'] = $login;
header('Location: index.php');
exit();
}
}
} else {
$errors[] = 'No data received';
}
include "includes/overall/overall_header.php";
if (empty($errors) === false) {
?>
<h2> We tried to log you in, but...</h2>
<?php
echo output_errors($errors);
}
?>
<center><input id="submit" type="submit" value="Back" onclick="location.href='Login2.php'"></center>
<?php
include "includes/overall/overall_footerloggedout.php";
?>
users.php
<?php
function logged_in() {
return (isset($_SESSION['studentid'])) ? true : false;
}
function user_exists($studentemail) {
$studentemail = sanitize($studentemail);
$query = mysql_query("SELECT COUNT(`studentid`) FROM `student` WHERE `studentemail`
= '$studentemail'");
return (mysql_result($query, 0) == 1) ? true : false;
}
function studentid_from_student ($studentemail) {
$studentemail = sanitize($studentemail);
return mysql_result(mysql_query("SELECT `studentid` FROM `student` WHERE `studentemail` = '$studentemail'"), 0, 'studentid');
}
`function login($studentemail, $studentpassword) {
$studentid = studentid_from_student($studentemail);
$studentemail = sanitize($studentemail);
$studentpassword = md5($studentpassword);
return (mysql_result(mysql_query("SELECT COUNT(`studentid`) FROM `student` WHERE `studentemail` = '$studentemail' AND `studentpassword` = '$studentpassword'"), 0) == 1) ? $studentid : false;
}
?>
I suggest to change your logic, extracting users and admins from two different table. Make them in only one table, but all users should contain column flag for example, where flag=1 is ADMIN and flag=0 is USER.
all i can suggest as i am not a php coder but have done some in the past is to add another field in your database where you will set levels of privileges for users (0 for normal members, 1 for admin). After you have done that just add it to your users script through php coding which i barely know. Hope that helps a little bit.

Help on how to continue with code that verifies a registered user and updates mySQL

When a user registers, the script sends an email to verify his account. Clicking on the link, the script gets the token
$token = mysql_real_escape_string($_GET["token"]);
and what I thought to do is
if($token != '') {
mysql_query("UPDATE members SET verified = '' WHERE verified = '$token'");
}
or
if($token != '') {
$result = mysql_query("UPDATE members SET verified = '' WHERE verified = '$token'");
if($result) { }
else { }
}
What is my purpose is to echo a success or failed message on the user. When it will be success then the verified will be empty.
What is the appropriate way of doing this with my examples above?
Should I check if there is the token in the DB before updating it?
Thank you.
Your current method updates a record if it exists but does not take into account that which does not exist or match. You should run something similar to:
if($token != '') {
$result = mysql_query("SELECT COUNT(*) FROM members WHERE verified = '$token'");
while($row = mysql_fetch_row($result)) {
$records = $row[0];
}
if($records == 0) { echo 'no results'; }
elseif($records ==1) { echo 'you matched'; then update the record. }
}
edit
changed BACK to the while loop, wasn't thinking of the count returning 0 rows

Categories