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.
Related
I am running into some issues with a query I am trying to make. What I am doing is trying to create a template for multiple pages to display specific images that correlate with that page.
I have individual pages where I am assigning a variable to define the page (you can see where I do this in my code with $page). Then within my database, under solution I am naming the specific records one of the individual page names. For example: if I named a page "Ball", under the database column solution, I would name a few records Ball.
Then within my query, I am trying to count how many records exist that match $page. If the record count is more than 0, I want to display the code in my else statement.
As of now, my database connection is working. I am not getting any errors being printed. You can see my echo $solution_count;. This is showing a 0, but my else-statement is running, which makes 0 sense.
Am I doing anything wrong with how I am trying to count the records? Does anyone see why this isn't working?
DB Table - show create table
projectslider
CREATE TABLE `projectslider` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`solution` varchar(50) NOT NULL,
`image` text NOT NULL,
`alt` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1
Code on the individual pages:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$page = "enclosures";
include_once("projectSlider.php");
?>
Master page - projectSlider.php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$servername = 'localhost';
$username = 'root';
$password = '';
try {
$con = new PDO('mysql:host='.$servername.';dbname=mb', $username, $password);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//$page = mysql_real_escape_string($page);
//SQL Call
$sql_project = "
SELECT *, COUNT(solution) AS solution_count
FROM projectslider
WHERE solution = '. $page .'
";
if ($project_stmt = $con->prepare($sql_project)) {
$project_stmt->execute();
$project_rows = $project_stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($project_rows as $project_row) {
$solution_count = $project_row['solution_count'];
echo $solution_count;
$project_solution = $project_row['solution'];
$project_img = $project_row['image'];
$project_alt = $project_row['alt'];
$project_img = '<img class="home-comment-profile-pic" src=" '. $project_img .'" alt="' . $project_alt .'">';
if ($solution_count === 0) {
echo 'No projects found.';
} else {
echo '<section id="solProj">';
echo '<div class="projSlide">';
echo $project_img;
echo '</div>';
echo '</div>';
}
}
}
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
One project have many sliders , for this you should have two tables projects and projectsliders with relationship.
projects table:
CREATE TABLE `projects` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`project_name` varchar(50) NOT NULL
)
projectsliders:
CREATE TABLE `projectsliders` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`solution` varchar(50) NOT NULL,
`image` text NOT NULL,
`alt` text NOT NULL,
`project_id` int(11),
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1
fetching projectSliders for one project, Master page - projectSlider.php
Best way to fetching projectsliders for one project is to use OOP you can call a method and pass project id and method should return you a array with projectsliders for this project , but i am improving your code.
error_reporting(E_ALL);
ini_set('display_errors', 1);
$servername = 'localhost';
$username = 'root';
$password = '';
try {
$con = new PDO('mysql:host='.$servername.';dbname=mb', $username,
$password);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//$page = mysql_real_escape_string($page);
//SQL Call
$sql_project = "SELECT * FROM projectsliders ps inner join projects p
on p.id = ps.project_id
WHERE p.project_name = '. $project_page .'";
if ($project_stmt = $con->prepare($sql_project)) {
$project_stmt->execute();
$count = project_stmt->rowCount();
if( $count != 0 ){
$project_rows = $project_stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($project_rows as $project_row) {
$project_solution = $project_row['solution'];
$project_img = $project_row['image'];
$project_alt = $project_row['alt'];
$project_img = '<img class="home-comment-profile-pic" src=" '.
$project_img .'" alt="' . $project_alt .'">';
echo '<section id="solProj">';
echo '<div class="projSlide">';
echo $project_img;
echo '</div>';
echo '</div>';
}
}else{
echo 'No projects found.';
}
}
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
Individual pages :
error_reporting(E_ALL);
ini_set('display_errors', 1);
$project_page = "enclosures";
include_once("projectSlider.php");
I hope that this can help you ,enjoying coding.
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();
I'm making a login, with ranks. When you are logged In you receive a welcome message. But that's diffrent for every rank.
my index.php:
<?php
include_once("config.php");
?>
<?php if( !(isset( $_POST['login'] ) ) ) { ?>
<?php
} else {
$usr = new Users;
$usr->storeFormValues( $_POST );
if( $usr->userLogin() ) {
echo "Welcome ";
if ($rank == 1) {
echo "default user";
}
if ($rank == 10) {
echo "developer! right?";
}
else {
echo "error";
}
} else {
echo "Incorrect Username/Password";
}
}
?>
but how do I get the user ranks?
my sql:
CREATE TABLE IF NOT EXISTS `users` (
`userID` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(50) NOT NULL,
`password` varbinary(250) NOT NULL,
`rank` varbinary(250) NOT NULL,
PRIMARY KEY (`userID`,`username`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=8 ;
how do I edit my code so I can get the rank of user?
Thanks!
EDIT AFTER Zsolt Szilagy's ANSWER:
$rank = 'SELECT rank FROM users WHERE userID = "' . mysql_real_escape_string($usr->get_userID()) . '"';
^^doesn't works^^ or am I doing it wrong?
'SELECT rank FROM users WHERE userID = "' . mysql_real_escape_string($usr->get_userID()) . '"';
Depending on your getters, on how the object was loaded, and on your db abstraction.
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'];
....
}
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.