May i know what is wrong with my phpcode? - php

This is what i have for headers.php anyway it is suppose to be my navigation bar. Here's the problem, when I login with a user as Member the whole header does not come out. But when I login with admin the navigations will "magically" come out!
<?php
if(!isset($_SESSION['sRole'])){
?>
<div id="header">
<div id="fb-root"></div>
<div id ="inthebox">
<b>LOGIN</b>|
<b>REGISTER</b>
</div>
<div id ="outthebox">
HOME|
BOOKSHELF|
SHOPPING CART|
ABOUT|
ABOUT|
</div>
</div>
<?php
}
else{
if($_SESSION['sRole'] == "member"){
?>
<div id="header">
<div id ="inthebox">
<b>LOGOUT</b>
</div>
<div id ="outthebox">
HOME|
BOOKSHELF|
SHOPPING CART|
ABOUT|
PROFILE
<?php
echo("You have Login as :" . $_SESSION['sUsername']);
?>
</div>
</div>
<?php
}else{
if($_SESSION['sRole']=="admin"){
?>
<div id="header">
<div id ="inthebox">
<b>LOGOUT</b>
</div>
<div id="outthebox">
HOME|
BOOKSHELF|
SHOPPING CART|
ABOUT|
Manage Account|
Manage Books|
Manage Orders|
<?php
echo("You have Login as :" . $_SESSION['sUsername']);
?>
</div>
</div>
<?php
}
}
}
?>
This is my doLogin.php page , maybe it might help anyone here to solve this. I store the id, username, firstname and last name into the session. Inside have alr . The website hor when I go in is no error one . no html code error or whatsoever. Just that it does not appear. However the words below the nav links will still come out.
<?php
//connect to database
include ('dbfunction.php');
if (!isset($_POST['Login'])) {
if (isset($_POST['username'])) {
//retrieve form data
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM users WHERE username='" . $username . "'AND password = '" . $password . "'";
$result = mysql_query($query) or die('The error :' . mysql_error());
$num_rows =mysql_num_rows($result);
if($num_rows == 0){
header('Location:login.php');
exit();
}
//if record is found, store id and username into session
else{
$row = mysql_fetch_array($result);
$_SESSION['sUsername'] = $row['username'];
$_SESSION['sRole'] = $row['role'];
$_SESSION['sFirst_name'] = $row['first_name'];
$_SESSION['sLast_name'] = $row['last_name'];
header('location:successful_login.php');//redirect to this page
exit();
}
}
else {
}
} else {
header('Location:successful_login.php');
exit();
}
mysql_close();
?>

I think the problem here is you are using } else { conditions, but then nesting an if statement inside of them. In fact it looks like you had some broken closing braces. Here is the revised code:
<?php if(!isset($_SESSION['sRole'])){ ?>
<div id="header">
<div id="fb-root"></div>
<div id ="inthebox">
<b>LOGIN</b>|
<b>REGISTER</b>
</div>
<div id ="outthebox">
HOME|
BOOKSHELF|
SHOPPING CART|
ABOUT|
ABOUT|
</div>
</div>
<?php } else if($_SESSION['sRole'] == "member") { ?>
<div id="header">
<div id ="inthebox">
<b>LOGOUT</b>
</div>
<div id ="outthebox">
HOME|
BOOKSHELF|
SHOPPING CART|
ABOUT|
PROFILE
<?php
echo("You have Login as :" . $_SESSION['sUsername']);
?>
</div>
</div>
<?php }else if($_SESSION['sRole']=="admin"){ ?>
<div id="header">
<div id ="inthebox">
<b>LOGOUT</b>
</div>
<div id="outthebox">
HOME|
BOOKSHELF|
SHOPPING CART|
ABOUT|
Manage Account|
Manage Books|
Manage Orders|
<?php
echo("You have Login as :" . $_SESSION['sUsername']);
?>
</div>
</div>
<?php
}

try this:
<?php if( (!isset($_SESSION['sRole'])) || (empty($_SESSION['sRole'])) || (is_null($_SESSION['sRole'])) ): ?>
<html>your code</html>
<?php else: ?>
<?php switch($_SESSION['sRole']) {
case 'admin': { // admin code } break;
case 'member': { // member code } break;
default: { // something happened } break;
}
?>
<?php endif; ?>
check and diagnose the issue

Related

Blank page when entering space in php search

When adding a name with a space in the search bar the header and the footer remains however the body disappears.
I even added ini_set('display_errors', '1') and ini_set( 'default_charset', 'UTF-8' ); to check for errors however that didn't help.
Please note that the function works fine except when when entering any spaces
Here is the code:
<?php
//ini_set('display_errors', '1');
//ini_set( 'default_charset', 'UTF-8' );
session_start();
$title="Search";
include('includes/connection.php');
$url=parse_url($_SERVER['REQUEST_URI'],PHP_URL_PATH);
$url_array=explode("/",$url);
$name=end($url_array);
$uname = urldecode($name);
$position="absolute";
$sql ="SELECT userName , firstName, lastName,id
FROM users
WHERE userName LIKE ?
or firstName like ?
or lastName Like ?
or concat(firstName,' ',lastName) = ?";
$params=array("$uname","$uname","$uname","$uname");
$query= $dbh -> prepare($sql);
if($query-> execute($params)){
$results=$query->fetchAll(PDO::FETCH_OBJ);
if($query->rowCount() > 6) {
$position="inherit";
} else {
$position="absolute";
}
}
if (!$results) {
$mess = true;
// echo '<script type="text/javascript">alert("Hi");</script>';
}
//else {
//$mess = true;
//$query->errorInfo();
//}
include('includes/header.php');
//else
//{
// $mess = $query->errorInfo();
// echo '<script type="text/javascript">alert("'.$mess[2].'");</script>';
//}
?>
<main role="main" class="mbr-fullscreen" style="display: grid;position: <?php echo $position;?>;">
<div class="album py-5" >
<div class="container">
<div class="row">
<?php
if(!$results) {
echo'<div class="col-lg-12 mx-auto">
<center>
<h1 style="padding: 10px; color: #575957;">No results found</h1>
<h6>We couldn\'t find any user matching your search</h6>
<a href="/index.php" class="btn btn-primary display-4" >Search Again</a>
</center>
</div> ';
}
?>
<?php
foreach($results as $result) {
?>
<div class="col-md-4">
<div class="card mb-4 shadow-sm">
<div class="card-body">
<h3 class="card-text text-center" style="text-transform: capitalize;"><?php echo htmlentities($result->userName);?></h3>
<p class="text-center"> <?php echo htmlentities ($result->firstName).' '; echo htmlentities ($result->lastName); ?> </p>
<div class="d-flex justify-content-between align-items-center">
<div class="btn-group mx-auto mbr-form">
View
</div>
</div>
</div>
</div>
</div>
<?php
}
?>
</div>
</div>
</div>
</main>
<?php include('includes/footer.php');?>
Like statement does not work like that. You should change your query in the proper format.
Replace:
$params=array("$uname","$uname","$uname","$uname");
With:
$params=array("%$uname%","%$uname%","%$uname%","%$uname%");
1. Add $uname=str_replace(" ", "% %", $uname); after $uname = urldecode($name); to wrap each space with %
2. Replace concat(firstName,' ',lastName) = ? With concat(firstName,' ',lastName) like ?
3. Follow Tahasin instructions, Replace $params=array("$uname","$uname","$uname","$uname"); with $params=array("%$uname%","%$uname%","%$uname%","%$uname%");
I solved the problem by adding the following line in the home page
search = search.replace(/\s/g,"-");
And in my search page, I added the following code
$name=str_replace('-',' ',$uname);
You people are great, thank you for helping me out

How to load any activity by default when Page loads?

Below is my Code where user after sucessfully login can enter into website, but then it shows empty with left and right sidebar
I want the dashboard activity to load by default as the user signed in. How can I do that.
Here it is an library managment system whre user can borrow , edit return books and all history is recorded.
<?php
session_start();
error_reporting(0);
include("databaseConnection.php");
$username = $_SESSION['username'];
if($_REQUEST['activity'] == 'logout'){
$username = null;
$username ="";
unset($username);
$_SESSION['username'] = null;
$_SESSION['username'] ="";
unset($_SESSION['username']);
session_destroy();
}
if(empty($username)){
header("location: ../Index.php");
}
?>
<html>
<head>
</head>
<body>
<!--CONTAINER AREA SECTION-->
<div class="containerHome">
<!--HEAD SECTION-->
<div class="headSection">
<?php include("headSection.php"); ?>
</div>
<!--HEAD SECTION-->
<div class="navSection">
<div class="welcomeTitle">Welcome</div>
<div class="tooltip">Contact Us
<span class="tooltiptext">
<b>Address:</b> Central Department Of Physics, Kirtipur<br>
<b>Phone:</b> 01-4331054
</span>
</div>
<div class="logoutLink">Logout</div>
</div>
<!--LEFT BAR SECTION-->
<div class="leftSection">
<?php include("leftSection.php");?>
</div>
<!--LEFT BAR SECTION-->
<!--CONTENT AREA SECTION-->
<div class="contentSection">
<?php
// CODE FOR PERFORMMING ACTIVITY..
$activity = $_REQUEST['activity'];
if($activity) {
if(isset($_POST['activity'])) {
include("dashboard.php");
}
if($activity) {
if($activity == 'addMember'){
include("addMember.php");
}
if($activity == 'dashboard'){
include("dashboard.php");
}
if($activity == 'issueBooks'){
include("issueBooks.php");
}
if($activity == 'returnBooks'){
include("returnBooks.php");
}
if($activity == 'updateBook'){
$uBookId = $_REQUEST['uBookId'];
$return = mysql_num_rows(mysql_query("SELECT bookId From borrow Where bookId = '$uBookId'"));
if(empty($return)){
$query = mysql_query("SELECT bookId,title,author,price,publisher From books Where bookId = '$uBookId'");
$result = mysql_fetch_assoc($query);
?>
</div>
<!--CONTENT AREA SECTION-->
<!--RIGHT AREA SECTION-->
<div class="rightSection">
<?php include("rightSection.php");?>
</div>
<!--RIGHT AREA SECTION-->
</div>
<!--CONTAINER AREA SECTION-->
</body>
</html>
Change code below
<?php
// CODE FOR PERFORMMING ACTIVITY..
$activity = $_REQUEST['activity'];
if(isset($activity) || empty($activity)) {
include("dashboard.php");
}
else {
if($activity == 'addMember'){
include("addMember.php");
.............your code............
My advice is DO NOT USE $_REQUEST use $_GET, $_POST instead.

How do I output two values from two different tables to a href?

I want to output something like this:
viewlogs.php?id=1&EmployeeNo=15000000600
However, I'm not sure what condition I should be using. I have two separate database to call, one is on MySQL which is easily taken to the localhost, and MSSQL which I'm not very familiar with.
I'm trying a logic where I use && within a while loop.
My code works something like this:
<?php
session_start();
if (!isset($_SESSION['username']))
{
header('location: login.php');
die();
}
?>
<?php
try {
include ("config.php");
include ("sqlsrv.php");
}catch(Exception $e){
die("ERROR:".$e->getMessage());
}
if(isset($_POST['usn']) && $_POST['usn']!=""){
$res = $conn->prepare("SELECT EmployeeNo, FirstName, MiddleName, LastName, DateHired, ResignationDate FROM TA3.dbo.Employees");
$res->execute();
$req = $db->prepare("SELECT * FROM students WHERE usn LIKE :usn");
$req->execute(array(
'usn'=>'%'.$_POST['usn'].'%'));
if ($req->rowCount()==0 && $_SESSION['type']=="Super_Admin") { ?>
<span class="notfound">Student not found? <a class="addstud" href="create.php">add student?</a></span>
<?php
}
elseif ($req->rowCount()==0 && $_SESSION['type']=="Admin") { ?>
<span class="henhen">Student not found</span>
<?php
}
else{
while ($data=$req->fetch() && $outcome=$res->fetch()){
?>
<div class="infohen">Info </div>
<div class="uy">
<div class="name"><?php echo $data['fname']." ".$data['mname']." ".$data['lname']; ?></div>
<div class="email"><?php echo $data['email']; ?></div>
<div class="usn"><?php echo $data['usn']; ?></div>
<div class="schedule"><?php echo $data['schedule']; ?></div>
<div class="strand"><?php echo $data['strand']; ?></div></div>
<?php if ($_SESSION['type']=="Super_Admin")
{ ?>
<div class="gridme">
<div class="action-list">
<div class="action">Action</div>
<div class="edit"> Edit</div>
<div class="logs">Logs</div>
<?php } else { ?>
<div class="gridme">
<div class="action-list">
<div class="action">Action</div>
<div class="logs">Logs</div>
<?php } ?>
</div>
</div>
</div>
</div>
<?php
}
}
}else { ?>
<span class="message">Enter USN!</span>
<?php
}
?>
<!-- <div class="enable"> <a onclick="return confirm('Are you sure you want to Enable student?')" href="enable.php?id=<?= $data['id']?>"> Enable </div>
<div class="disable"> <a onclick="return confirm('Are you sure you want to disable student?')" href="disable.php?id=<?= $data['id']?>">Disable</a>
</div> -->
<!-- </div>
<div class="status-list">
<div class="status">Status</div>
<div class="active">Active</div>
</div> -->
If I use while ($data=$req->fetch() && $outcome=$res->fetch()), the details called from $data are all gone.
I'm having trouble with logic since I'm not very good at it.
If anyone might need it, I found a solution.
I just needed to use open and close parenthesis.
while (($data=$req->fetch()) && ($outcome=$res->fetch()))

How to Implement Login/ PHP Web App within Wordpress

I've included a manual php file inside the template folder of wordpress.
Then created a page of its type in wordpress.
Then the user interface related to the specific php file will be displayed.
It contains a simple login functionality.
When the username and password is matched, it should redirect to the next php welcome page. Instead it reloads itself.
How to load the next php file to this page ?
<?php
include("config.php");
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST") {
// username and password sent from form
$myusername = mysqli_real_escape_string($db,$_POST['username']);
$mypassword = mysqli_real_escape_string($db,$_POST['password']);
$sql = "SELECT varEmail FROM tblUser WHERE varEmail = '$myusername' and varPassword = '$mypassword'";
$result = mysqli_query($db,$sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$active = $row['active'];
$count = mysqli_num_rows($result);
$error = "Inside";
// If result matched $myusername and $mypassword, table row must be 1 row
if($count == 1) {
wp_redirect( 'http://www.example.com', 302 );//exit;
$error = "{$myusername}{':'}{$mypassword }";
}else {
$error = "Your Login Name or Password is invalid";
}
}
?>
<?php
/*
Template Name: Online Survey
*/
get_header();
?>
<?php
$page_title = get_post_meta($post->ID, 'iweb_page_title', TRUE);
$mb_portfolio = get_post_meta($post->ID, 'iweb_page_portfolio', TRUE);
$mb_signup = get_post_meta($post->ID, 'iweb_page_signup', TRUE);
$mb_clients = get_post_meta($post->ID, 'iweb_page_clients', TRUE);
?>
<!-- PAGE TITLE -->
<div class="container clearfix">
<div class="sixteen columns">
<div class="page-title-container clearfix">
<?php if ($page_title != '') { ?>
<h1 class="page-title"><?php echo $page_title; ?></h1>
<?php } else { ?>
<?php get_template_part('includes/breadcrumbs'); ?>
<?php } ?>
</div>
</div>
</div>
</div> <!-- Grey bg end -->
<div class="clearfix">
<div class="m-bot-10">
<?php if(iwebtheme_smof_data('map_enable') != 0) { ?>
<!-- Google Maps -->
<section class="google-map-container">
<div id="googlemaps" class="google-map"></div>
</section>
<!-- Google Maps / End -->
<?php } ?>
</div>
</div>
<!-- CONTACT FORM-->
<div class="container clearfix">
<div class="ten columns m-bot-35">
<form action = "" method = "post">
<label>Email :</label><input type = "text" name = "username" class = "box"/><br /><br />
<label>Password :</label><input type = "password" name = "password" class = "box" /><br/><br />
<input type = "submit" value = " Submit "/><br />
</form>
<div style = "font-size:11px; color:#cc0000; margin-top:10px"><?php echo $error; ?></div>
</div>
</div>
<?php if($mb_portfolio != 'Disable') { ?>
<?php get_template_part( 'includes/part-portfolio' ); ?>
<?php } ?>
<?php if($mb_signup != 'Disable') { ?>
<?php get_template_part( 'includes/part-newsletter' ); ?>
<?php } ?>
<?php if($mb_clients != 'Disable') { ?>
<?php get_template_part( 'includes/part-clients' ); ?>
<?php } ?>
How can I load the welcoome.php file ?
wp_redirect( 'http://www.example.com', 302 );//exit;
It's hosted shared. Is it possible to create a php web application alongside wordpress , and call that application inside php or redirect a php page to the web application ?
Login is successful, but I cannot load the other pages. Or should I load them dynamically ?

Applying pagination to search results using Zend Paginator

I've searched through similar questions but to no avail, so hopefully someone can help.
I'm having an issue paginating the search results on a site I've built using the Zend Framework (1.12). I can retrieve the items and also the pagination is formed but when I click to go to the next page of pagination, all the search results are lost. The code appends ?page=2 e.t.c to the URL but the code then loses the searchitems.
I read in one question about possibly using sessions or Zend_Session in particular but I'm a little lost at present! Relatively new to PHP.
Firstly here is my search form - search-form.php (XHTML)
<?php
// Search Form
?>
<div id="search">
<h4 style="margin-bottom:20px;">Search</h4>
<form name="prodSearch" action="listing-search.php" method="post">
<input type="text" name="searchitems" id="searchitems" />
<input type="submit" name="search_items" id="search_items" value="Go" />
</form>
</div>
This is included in my other pages.
listing-search.php is then as follows
<?php
require_once('admin/scripts/library.php');
require_once('admin/scripts/db_definitions.php');
try {
?>
<!-- HTML Doc Type, Head removed e.t.c -->
<div id="listing-col-main">
<div id="all-cars">
<h4>Search Results</h4>
</div>
<!-- Listings -->
<?php
$query = $_POST['searchitems'];
$min_length = 3;
if (strlen($query) >= $min_length) {
$query = htmlspecialchars($query);
$query = mysql_real_escape_string($query);
$raw = searchItems($dbread, $query);
$paginator = Zend_Paginator::factory($raw);
if (isset($_GET['page'])) {
$paginator->setCurrentPageNumber($_GET['page']);
}
$paginator->setItemCountPerPage(8);
$paginator->setPageRange(3);
$count = $paginator->getTotalItemCount();
if ($count > 0) {
foreach ($paginator as $results) { // repeat all results ?>
<?php
$item_id = $results['item_id'];
$photos = getRelatedPhotos2($dbread, $item_id);
?>
<div class="product-listing">
<div class="product-listing-image">
<?php foreach ($photos as $photo) { //repeat ?>
<img src="image_upload/<?php echo $photo['filename']; ?>" width="75" alt="" />
<?php } ?>
</div>
<div class="product-listing-title">
<h4><?php echo $results['type_name']; ?> - <?php echo $results['item_make'] . ' ' . $results['item_model']; ?> </h4>
</div>
<div class="product-listing-details">
<p>YEAR: <?php echo $results['item_year']; ?> FUEL: <?php echo $results['item_fuel']; ?> TRANS: <?php echo $results['item_transmission']; ?> MILEAGE: <?php echo $results['item_mileage']; ?> </p>
</div>
<div class="product-listing-viewmore">More Info</div>
</div>
<?php } ?>
<!-- 8 products per page -->
<div id="product-listing-pagination">
<?php
$pages = $paginator->getPages('Elastic');
if (isset($pages->previous)) {
echo 'Prev';
}
foreach ($pages->pagesInRange as $page) {
if ($page != $pages->current) {
echo " <a href='" . $_SERVER['PHP_SELF'] . "?page={$page}'>$page</a>";
} else {
echo ' ' . $page;
}
}
if (isset($pages->next)) {
echo ' Next';
}
?>
</div>
<?php } else { ?>
<div id="noresults"> <?php echo "No results found for " . $query; ?> </div>
<?php }
} ?>
</div>
<div id="col-right">
<?php include("search-usedcars.php"); ?>
<!-- End of Main Search -->
<div id="latest-news">
<h3>Latest News</h3>
<?php include("latestnews.php"); ?>
</div>
</div>
<div class="clear"></div>
<div id="footer-bar"> Designed by </div>
</div>
</body>
</html>
<?php
} catch (Exception $e) {
echo $e->getMessage();
}
?>
It is because your query is passed in $_POST, when you click your nav links away you loose the data stored in $_POST and only keep what is in $_GET. Either change your search form method to $_GET and add &searchitems="'.$query.'" to both your nav links, or store the query in $_SESSION, or you can change your nav links to buttons wrapped in forms with method post and include hidden fields for searchitems and page. I would advise changing the search form method to get as it allows the bookmarking of searches and avoids complexity.

Categories