SQLSTATE[HY093]:Invalid parameter number:parameter was not defined - php

Problem came multiple times, but I really can not find the mistake in my code. I saw that the solutions are in misspelled words usually, but I can not find that. So I thought that maybe I am wrong in something other because I am new in using PDO.
I am making signup page and error is
SQLSTATE[HY093]: Invalid parameter number: parameter was not defined
here is my code:
//index.php
if(isset($_POST['btn-signup-preduzece'])) {
$uname = trim($_POST['pr-username']); //there are inputs in my html
$umail = trim($_POST['pr-email']);
$upass = trim($_POST['pr-password']);
$comp = trim($_POST['pr-naziv']);
$maticni = trim($_POST['pr-maticni']);
$pib = trim($_POST['pr-pib']);
$sifra = trim($_POST['pr-sifra']);
$racun = trim($_POST['pr-racun']);
$adresa = trim($_POST['pr-adresa']);
if($uname=="") {
$error[] = "provide username !";
}
else if($umail=="") {
$error[] = "provide email id !";
}
else if(!filter_var($umail, FILTER_VALIDATE_EMAIL)) {
$error[] = 'Please enter a valid email address !';
}
else if($upass=="") {
$error[] = "provide password !";
}
else {
try {
$stmt = $DB_con->prepare("SELECT username,email FROM preduzeca WHERE username=:uname OR email=:umail");
$stmt->execute(array(':uname'=>$uname, ':umail'=>$umail));
$row=$stmt->fetch(PDO::FETCH_ASSOC);
if($row['username']==$uname) {
$error[] = "sorry username already taken !";
}
else if($row['email']==$umail) {
$error[] = "sorry email id already taken !";
}
else {
//PROBLEM IS HERE IN THIS FUNTION BELLOW, when I put here some echo it writes me that, but if i put echo bellow this if statement it gives me nothing
if($user->registerPreduzece($uname,$upass,$umail, $comp, $maticni, $pib, $sifra, $racun, $adresa)) {
$user->redirect('ostalo/uspesno.php');
}
}
}
catch(PDOException $e) {
echo $e->getMessage();
}
}
}
and here is my problematic function form class User
public function registerPreduzece($uname,$upass,$umail, $comp, $maticni, $pib, $sifra, $racun, $adresa) {
try
{
$new_password = password_hash($upass, PASSWORD_DEFAULT);
$stmt = $this->db->prepare("INSERT INTO preduzeca(naziv,maticniBroj,PIB,sifraDelatnosti,racun,adresa,username,password,email)
VALUES(:comp, :maticni, :pib, :sifra, :racun, :adresa, :uname, :upass, :umail)");
$stmt->bindparam(":naziv", $comp);
$stmt->bindparam(":maticniBroj", $maticni);
$stmt->bindparam(":PIB", $pib);
$stmt->bindparam(":sifraDelatnosti", $sifra);
$stmt->bindparam(":racun", $racun);
$stmt->bindparam(":adresa", $adresa);
$stmt->bindparam(":username", $uname);
$stmt->bindparam(":password", $new_password);
$stmt->bindparam(":email", $umail);
$stmt->execute();
return $stmt;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
and my table
CREATE TABLE `preduzeca` (
`idPreduzeca` int(10) UNSIGNED NOT NULL,
`naziv` varchar(45) NOT NULL,
`maticniBroj` varchar(8) DEFAULT NULL,
`PIB` varchar(11) DEFAULT NULL,
`sifraDelatnosti` varchar(5) DEFAULT NULL,
`racun` varchar(20) DEFAULT NULL,
`adresa` int(11) DEFAULT NULL,
`username` varchar(45) NOT NULL,
`password` varchar(45) NOT NULL,
`email` varchar(45) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
ALTER TABLE `preduzeca`
ADD PRIMARY KEY (`idPreduzeca`),
ADD UNIQUE KEY `idfirme_UNIQUE` (`idPreduzeca`),
ADD UNIQUE KEY `username_UNIQUE` (`username`),
ADD UNIQUE KEY `maticniBroj_UNIQUE` (`maticniBroj`),
ADD UNIQUE KEY `PIB_UNIQUE` (`PIB`),
ADD UNIQUE KEY `racun_UNIQUE` (`racun`),
ADD KEY `fk_preduzeca_adrese1_idx` (`adresa`);

The binding of your parameters seems to be off. Try instead
$stmt = $this->db->prepare("INSERT INTO preduzeca(naziv,maticniBroj,PIB,sifraDelatnosti,racun,adresa,username,password,email)
VALUES(:comp, :maticni, :pib, :sifra, :racun, :adresa, :uname, :upass, :umail)");
$stmt->bindparam(":comp", $comp);
$stmt->bindparam(":maticni", $maticni);
$stmt->bindparam(":pib", $pib);
$stmt->bindparam(":sifra", $sifra);
$stmt->bindparam(":racun", $racun);
$stmt->bindparam(":adresa", $adresa);
$stmt->bindparam(":uname", $uname);
$stmt->bindparam(":upass", $new_password);
$stmt->bindparam(":umail", $umail);
$stmt->execute();

Related

PHP PDO & MySQL * WHERE OR AND statement issue

I am currently trying to find out why my login statement works with using a username, but not email (or vice versa if switch in query)
The query only seems to accept the first value of the query, even if I've put it in brackets, it doesn't seem to register the second parameter.
Running the query in phpMyAdmin works flawlessly, but breaks in the script
open to suggestions
$sql = "SELECT * FROM db_cms_users WHERE username = ? OR email = ? AND password = ?";
$stmt = $this->connect()->prepare($sql);
if(!$stmt->execute([$userID, $userID, $password])){
$stmt = null;
header("location: index.php?error=failstmt");
exit();
}
if($stmt->rowCount() == 0){
$stmt = null;
header("location: login.php?error=nouser");
exit();
}
I have tried
$sql = "SELECT * FROM db_cms_users WHERE (username = ? OR email = ?) AND password = ?";
rowCount returns true if I input a username, but false if I input a email. statements match SQL Database.
Dumped Variables
SQL: [76] SELECT * FROM db_cms_users WHERE username = ? OR email = ? AND password = ?
Sent SQL: [137] SELECT * FROM db_cms_users WHERE username = 'test#email.com' OR email = 'test#email.com' AND password = 'password'
Params: 3
Key: Position #0: paramno=0 name=[0] "" is_param=1 param_type=2
Key: Position #1: paramno=1 name=[0] "" is_param=1 param_type=2
Key: Position #2: paramno=2 name=[0] "" is_param=1 param_type=2
Database output
Array
(
[0] => Array
(
[id] => 1
[0] => 1
[username] => test
[1] => test
[password] => $2y$10$QNKXEo3pnGPCjUMnfXlV..JJ4OFcSQJ5EVg75xOjlE7p5pL7Dqwau
[2] => $2y$10$QNKXEo3pnGPCjUMnfXlV..JJ4OFcSQJ5EVg75xOjlE7p5pL7Dqwau
[email] => test#email.com
[3] => test#email.com
[status] => 1
[4] => 1
[is_admin] => 1
[5] => 1
[registration] => 2021-11-13 12:21:28
[6] => 2021-11-13 12:21:28
)
)
File: user.class.php
protected function loginUser($userID, $password){
$sql = "SELECT password FROM db_cms_users WHERE username = ? OR email = ?";
$stmt = $this->connect()->prepare($sql);
if(!$stmt->execute([$userID, $userID])){
$stmt = null;
header("location: index.php?error=failstmt");
exit();
}
if($stmt->rowCount() == 0){
$stmt = null;
header("location: login.php?error=loginerror");
exit();
}
$hashedPwd = $stmt->fetchAll();
$checkPwd = password_verify($password, $hashedPwd[0]['password']);
if($checkPwd == false){
$stmt = null;
header("location: index.php?error=wrongpwd");
exit();
}elseif($checkPwd == true){
$sql = "SELECT * FROM db_cms_users WHERE username = ? OR email = ? AND password = ?";
$stmt = $this->connect()->prepare($sql);
if(!$stmt->execute([$userID, $userID, $password])){
#$stmt = null;
header("location: index.php?error=failstmt");
exit();
}
if($stmt->rowCount() == 0){
$stmt = null;
header("location: login.php?error=nouser");
exit();
}
$row = $stmt->fetchAll();
//make session later
//nov 13/21
session_start();
$_SESSION['username'] = $row[0]['username'];
$_SESSION['uid'] = $row[0]['id'];
return true;
}
}
File userContr.class.php
public function login($userID, $password){
$result = $this->loginUser($userID, $password);
return $result;
}
File test.php
<?php
ob_start();
session_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
include "includes/autoloader.inc.php";
$userObj = new UserView();
$data = $userObj->showUser(1);
echo "<pre>";
print_r ($data[0]);
echo "</pre>";
$userObj = new UserContr();
if(isset($_SESSION['uid'])){
echo "<h1>Welcome back ". $_SESSION['username'] ."!";
echo "<a href='?a=logout'>Logout</a>";
if(isset($_GET['a'])){
$a = $_GET['a'];
if($a == "logout"){
$userObj->logoutUser();
exit();
}
}
}else{
if(isset($_POST['loginUser'])){
$userID = $_POST['userid'];
$password = $_POST['password'];
$result = $userObj->login($userID, $password);
if($result == true){
header("location: index.php");
exit();
}else{
echo "There was a login error";
exit();
}
}else{
echo "<h1>Login</h1>";
echo "<form method='post' action>
<input type='text' name='userid' placeholder='Username/Email'>
<input type='password' name='password' placeholder='password'><br>
<input type='submit' name='loginUser' value='Login'>
</form>";
}
}
ob_end_flush();
SQL: Dump file
-- Table structure for table `db_cms_users`
--
CREATE TABLE `db_cms_users` (
`id` int(11) NOT NULL,
`username` text NOT NULL,
`password` text NOT NULL,
`email` text NOT NULL,
`status` int(11) NOT NULL DEFAULT '0',
`is_admin` int(11) NOT NULL DEFAULT '0',
`registration` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `db_cms_users`
--
INSERT INTO `db_cms_users` (`id`, `username`, `password`, `email`, `status`, `is_admin`, `registration`) VALUES
(1, 'test', '$2y$10$QNKXEo3pnGPCjUMnfXlV..JJ4OFcSQJ5EVg75xOjlE7p5pL7Dqwau', 'test#email.com', 1, 1, '2021-11-13 20:21:28');
Thanks for the big update. The context is very useful. It seems like what you're trying to do isn't logical or necessary.
To begin with, everything starts off well. In your loginUser() function, you're correctly fetching the user details based on the email / username. Then you're verifying the password the right way using password_verify(). That's all fine and sensible.
But the bit you seem to be having trouble with doesn't make a whole lot of sense. It looks like after you've verified the password, you then make another query to get the same user - except that this time you're trying to put the password into the WHERE clause. This makes no sense because
You've already found the user with the first query and verified them, and
the raw password will never match the one in the database because the one in the database is hashed (as it should be, hence why you used password_verify() earlier in the code).
You really don't need that second SELECT query - what are you trying to achieve with it?
If you just change the first query to select more fields, then your problem is solved - you can put those details directly into the Session without needing to run another query:
protected function loginUser($userID, $password) {
$sql = "SELECT username, id, password FROM db_cms_users WHERE username = ? OR email = ?";
$stmt = $this->connect()->prepare($sql);
if(!$stmt->execute([$userID, $userID])) {
$stmt = null;
header("location: index.php?error=failstmt");
exit();
}
if($stmt->rowCount() == 0) {
$stmt = null;
header("location: login.php?error=loginerror");
exit();
}
$user = $stmt->fetchAll();
$checkPwd = password_verify($password, $user[0]['password']);
if($checkPwd == false) {
header("location: index.php?error=wrongpwd");
exit();
}
elseif($checkPwd == true) {
session_start();
$_SESSION['username'] = $user[0]['username'];
$_SESSION['uid'] = $user[0]['id'];
return true;
}
}
P.S. Security best practice recommends that when the credentials are not valid you don't let the user know whether it was the username or password (or both) which was the problem. For example if you disclose that the username was wrong, it indicates to a malicious party that they can discard that username and try another one, and equally if you disclose that only the password is incorrect you are indicating that they should keep attempting to crack the password for that username. You should simply state "invalid credentials" in either case, which then does not give any clues about how to narrow the search for a valid login.

GET User ID to show catergories

I am trying to show only categories a user can see by assigning a the category ID inside of the user table.
I am logging in using the following script:
login.php
<?
session_start();
if(isset($_SESSION['user'])){
header("Location:home.php");
exit;
}
$dbh=new PDO('mysql:dbname=dashboardr;host=######', '######', '######');
$email=$_POST['username'];
$password=$_POST['pass'];
if(isset($_POST) && $email!='' && $password!=''){
$sql=$dbh->prepare("SELECT * FROM user_login WHERE username=?");
$sql->execute(array($email));
while($r=$sql->fetch()){
$p=$r['password'];
$p_salt=$r['psalt'];
$id=$r['id'];
$email=$r['username'];
$firstname=$r['firstname'];
$lastname=$r['lastname'];
}
$site_salt="subinsblogsalt";
$salted_hash = hash('sha256',$password.$site_salt.$p_salt);
if($p==$salted_hash){
$_SESSION['user']=$id;
$_SESSION['username']=$email;
$_SESSION['firstname']=$firstname;
$_SESSION['lastname']=$lastname;
header("Location:home.php");
}else{
echo "<h2>Username/Password is Incorrect.</h2>";
}
}
?>
Inside of the home.php file where it shows you are logged in here is where I need to show the categories which are inside of the 'cat_no' column which lised inside of the 'user_login' table.
Here is where I am wanting to GET the users ID and display those categories.
home.php
<?php require_once '../db_con.php';
if(!empty($_GET['user_id'])){
$cat = intval($_GET['user_id']);
try{
$results = $dbh->prepare("SELECT * FROM user_login WHERE FIND_IN_SET(?, cat_no)");
$results->bindParam(1, $cat);
$results->execute();
var_dump($cat);
} catch(Exception $e) {
echo $e->getMessage();
die();
}
$doc = $results->fetchAll(PDO::FETCH_ASSOC);
if($doc == FALSE){
echo '<div class="container">';
echo "<img src='../img/404.jpg' style='margin: 40px auto; display: block;' />";
echo "<h1 style='margin: 40px auto; display: block; text-align: center;' />Oh Crumbs! You upset the bubba!</h1>";
echo 'Get me outta here!';
echo'</div>';
die();
}
}
?>
My tables look like the following:
CREATE TABLE `cat_list` (
`cat_id` int(11) NOT NULL,
`cat_title` varchar(32) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf16 AUTO_INCREMENT=5 ;
CREATE TABLE `user_login` (
`id` int(11) NOT NULL,
`username` text NOT NULL,
`firstname` varchar(30) NOT NULL,
`lastname` varchar(50) NOT NULL,
`password` varchar(64) NOT NULL,
`psalt` text NOT NULL,
`col_no` text NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=12 ;
I am confused on how to GET the logged in users Id and show the categories which are listed out inside of the col_no column in the user_login table.

Php database handling

I'm working on a php page that compare information received by a client with information in a database, but I'm not so good in php and I don't know what I did wrong, I always get response code 500, internal server error.
Here is the code:
<?php
/**
* #var object $payload The payload sent from the client
*/
$payload = json_decode(file_get_contents("php://input"), true);
/**
* #var object $user_name The username sent by the client
* #var object $user_name The password sent by the client
*/
$user_name = $payload['username'];
$user_password = $payload['password'];
$response = null;
$responseCode = 200;
$result_row = null;
/**
* The form representing a positive response
*/
class Response {
public $accessToken = "";
public $availableProfiles = "";
public $selectedProfile = "";
}
/**
* The form representing a negative response
*/
class negativeResponse {
public $error = "";
public $errorMessage = "";
}
/**
* #var object $db_connection The database connection
*/
$db_connection = null;
try {
$db_connection = new PDO('mysql:host=localhost;dbname=launcher_login;charset=utf8', 'myUser', 'myPass');
} catch (PDOException $e) {
//Catch exception
}
// user can login with his username or his email address.
// if user has not typed a valid email address, we try to identify him with his user_name
if (!filter_var($user_name, FILTER_VALIDATE_EMAIL)) {
// database query, getting all the info of the selected user
$query_user = $this->db_connection->prepare('SELECT * FROM users WHERE user_name = :user_name');
$query_user->bindValue(':user_name', $user_name, PDO::PARAM_STR);
$query_user->execute();
// get result row (as an object)
$result_row = $query_user->fetchObject();
// if user has typed a valid email address, we try to identify him with his user_email
} else {
// database query, getting all the info of the selected user
$query_user = $db_connection->prepare('SELECT * FROM users WHERE user_email = :user_email');
$query_user->bindValue(':user_email', trim($user_name), PDO::PARAM_STR);
$query_user->execute();
// get result row (as an object)
$result_row = $query_user->fetchObject();
}
// if this user not exists
if (!isset($result_row->user_id)) {
$response = new negativeResponse();
$response->error = "Credenziali Invalide";
$response->errorMessage = "Non esiste un account con questa combinazione nome utente/password";
$responseCode=201;
// if the password isn't correct
} else if (!password_verify($user_password, $result_row->user_password_hash)) {
$response = new negativeResponse();
$response->error = "Credenziali Invalide";
$response->errorMessage = "Non esiste un account con questa combinazione nome utente/password";
$responseCode=201;
// if the account exists but it isn't activated
} else if ($result_row->user_active != 1) {
$response = new negativeResponse();
$response->error = "Account non attivo";
$response->errorMessage = "Devi attivare l'account! Controlla l'email inserita";
$responseCode=201;
} else {
$response = new Response();
$response->accessToken = hash('md5', $user_name);
$response->availableProfiles = array(array('id' => hash('md5', $user_name), 'name' => $user_name, 'legacy' => true));
$response->selectedProfile = array('id' => hash('md5', $user_name), 'name' => $user_name, 'legacy' => true);
}
echo json_encode($response);
http_response_code($responseCode);
My table is created with this query:
CREATE TABLE IF NOT EXISTS `launcher-login`.`users` (
`user_id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'auto incrementing user_id of each user, unique index',
`user_name` varchar(64) COLLATE utf8_unicode_ci NOT NULL COMMENT 'user''s name, unique',
`user_password_hash` varchar(255) COLLATE utf8_unicode_ci NOT NULL COMMENT 'user''s password in salted and hashed format',
`user_email` varchar(64) COLLATE utf8_unicode_ci NOT NULL COMMENT 'user''s email, unique',
`user_active` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'user''s activation status',
`user_activation_hash` varchar(40) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'user''s email verification hash string',
`user_password_reset_hash` char(40) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'user''s password reset code',
`user_password_reset_timestamp` bigint(20) DEFAULT NULL COMMENT 'timestamp of the password reset request',
`user_rememberme_token` varchar(64) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'user''s remember-me cookie token',
`user_failed_logins` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'user''s failed login attemps',
`user_last_failed_login` int(10) DEFAULT NULL COMMENT 'unix timestamp of last failed login attempt',
`user_registration_datetime` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`user_registration_ip` varchar(39) COLLATE utf8_unicode_ci NOT NULL DEFAULT '0.0.0.0',
PRIMARY KEY (`user_id`),
UNIQUE KEY `user_name` (`user_name`),
UNIQUE KEY `user_email` (`user_email`)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='user data';
EDIT: I feel stupid, the error was $query_user = $this->db_connection->prepare('SELECT * FROM users WHERE user_name = :user_name');. I was using this outside of a class, now I'm working on the client part, thank you all for help
I'm almost certain the issue is that $db_connection is null since the connection is failing. Based on what you provided your database name should be launcher-login instead of launcher_login as you've specified in your connection string. As such the following edit should fix your problem.
try {
$db_connection = new PDO('mysql:host=localhost;dbname=launcher-login;charset=utf8', 'myUser', 'myPass');
} catch (PDOException $e) {
echo 'Unable to connect to database'; exit;
}

store a mysql array records in session

I have a school web application ..
I want to get all the student name on the log_in.php pages in $_SESSION['allStudent']
for retrieve on further page...
here is my log in .php pages content
include("connect.php");
if(isset($_REQUEST['submit']))
{
$id=$_REQUEST['userName'];
$pass=$_REQUEST['password'];
$sel=mysql_query("select * from login_detail where USERNAME='$id' AND PASSWORD='$pass'")or die(mysql_error());
if($arr=mysql_fetch_array($sel))
{
if(($id==$arr['USERNAME']) && ($pass==$arr['PASSWORD']))
{
session_start();
$_SESSION['id']=$id;
$query = "SELECT * FROM student_personal";
$result = mysql_query($query) or die(mysql_error());
if($result)
{
$_SESSION['allStudent']['']= mysql_fetch_array($result);
}
header("location: viewPages/common/main.php?active=dashboard");
}
}
else
{
echo "<script>alert('please enter the correct id and password');</script>";
}
}
and retrieve into main page
this is my main pages
{
//designed Part
}
<?php
if(isset($_SESION['allStudent']))
{
echo "------------------------------------------<br>";
echo "Student Name--------------------------- DOB<br>";
echo "------------------------------------------<br>";
while($row = mysql_fetch_array($_SESSION['allStudent']))
{
echo $row['STUDENT_NAME']." --------------".$row['DOB']."<br>";
}
}
else
{
echo "No result Found";
}
?>
and this is my table
DB NAME : testssdb
Table Name : student_personal
`SR_NUMBER` int(11) NOT NULL,
`STUDENT_NAME` varchar(30) NOT NULL,
`GENDER` int(11) NOT NULL,
`DOB` varchar(25) NOT NULL,
`RELIGION` varchar(30) NOT NULL,
`MAILING_ADDRESS` text NOT NULL,
`TELEPHONE_NO` varchar(22) default NULL,
`MOBILE_NO` varchar(25) default NULL,
`EMAIL` varchar(30) default NULL,
`PERMANENT_ADDRESS` text,
`MOTHER_TONGUE` varchar(30) default NULL,
`CATEGORY` int(11) default NULL,
`STATUS` int(11) NOT NULL default '1',
`REG_DATE` date NOT NULL,
`FIRST_NAME` varchar(25) NOT NULL,
`LAST_NAME` varchar(25) NOT NULL,
PRIMARY KEY (`SR_NUMBER`)
Here $student = $firstname.$lastName;
So basically i want to store all student records on log in and anyneed of student,i do not want to intrect with the database. only use of session i get the student information
session_start();
$_SESSION['count'] = 1;
$_SESSION['record'][$_SESSION['count']] = array();
$query //retrive ur data here
$result set of ur query
while ($row = mysql_fetch_assoc($result))
{
$_SESSION['record'][$_SESSION['count']]['SR_NUMBER'] = $row["SR_NUMBER"];
$_SESSION['record'][$_SESSION['count']]['STUDENT_NAME'] = $row["STUDENT_NAME"];
$_SESSION['record'][$_SESSION['count']]['GENDER'] = $row["GENDER"];
$_SESSION['record'][$_SESSION['count']]['DOB'] = $row['DOB'];
...// and go on
$_SESSION['count'] = $_SESSION['count'] + 1;
}
foreach($_SESSION['record'] as $key => $value)
{
echo $value['SR_NUMBER'];
echo $value['STUDENT_NAME'];
echo $value['GENDER'];
echo $value['DOB'];
....
}

user level issue with redirecting [duplicate]

This question already exists:
Closed 10 years ago.
Possible Duplicate:
checklogin condition issue in php
i have this quick question please,
i have this piece of code which isn't working properly, something about the syntax.. could you please help me with it?
i know it may sound stupid enough but i'm trying to understand!
Thanks!
<?php
session_start();
require_once('db.php');
include('functions.php');
if (checkLogin('1 2')) {
echo "hello ".$_SESSION['user_id']." You are now logged in.";
} else if (checkLogin('3')) {
echo "hey tst";
} else {}
?>
function checkLogin($levels)
{
if(!$_SESSION['logged_in'])
{
$access = FALSE;
}
else {
$kt = split(' ', $levels);
$query = mysql_query('SELECT Level_access FROM users WHERE ID = "'.mysql_real_escape_string($_SESSION['user_id']).'"');
$row = mysql_fetch_assoc($query);
$access = FALSE;
while(list($key,$val)=each($kt))
{
if($val==$row['Level_access'])
{//if the user level matches one of the allowed levels
$access = TRUE;
}
}
}
if($access==FALSE)
{
header("Location: login.php");
}
else {
//do nothing: continue
}
}
CREATE TABLE `users` (
`ID` int(11) NOT NULL auto_increment,
`Username` varchar(255) NOT NULL,
`Password` varchar(255) NOT NULL,
`Temp_pass` varchar(55) default NULL,
`Temp_pass_active` tinyint(1) NOT NULL default '0',
`Email` varchar(255) NOT NULL,
`Active` int(11) NOT NULL default '0',
`Level_access` int(11) NOT NULL default '2',
`Random_key` varchar(32) default NULL,
PRIMARY KEY (`ID`),
UNIQUE KEY `Username` (`Username`),
UNIQUE KEY `Email` (`Email`)
) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
Well you could simplify your checkLogin() function
function checkLogin($levels)
{
$access = false;
if (!isset($_SESSION['logged_in']) || !$_SESSION['logged_in'])
return false;
//use mysqli instead mysql
$con = new mysqli("localhost", "username", "password", "database");
$query = $con->query('SELECT Level_access FROM users WHERE ID = "'.$con->real_escape_string($_SESSION['user_id']).'"');
$row = $query->fetch_assoc();
$con->close();
if (in_array($row['Level_access'], explode(" ", $levels))) $access = true;
return $access;
}
This function should return true or false!
After that your code could look like this
session_start();
require_once('db.php');
include('functions.php');
if (checkLogin('1 2')) {
echo "hello ".$_SESSION['user_id']." You are now logged in.";
} else if (checkLogin('3')) {
echo "hey tst";
} else {
header("Location: login.php");
}
Hope this helps you.
Your if statements need parenthesis around them:
if( checkLogin('1 2')) {
^ ^
Try this
<?php
session_start();
require_once('db.php');
include('functions.php');
if (checkLogin('1 2')) {
echo "hello ".$_SESSION['user_id']." You are now logged in.";
} else if (checkLogin('3')) {
echo "hey tst";
} else {}
?>
Run the code in your browser. You'll get an error message. Use that error message to figure out what's wrong. Repeat until you get no error messages, and the program runs as designed.
That's how we debug things in the real world.

Categories