I have been follwing a series of tutorials over at [thedigitalcraft.com][1] building my first ever dynamic website. I recently followed his 15th, and thought I followed along greatly, but for some reason the content that should be showing up isn't when I run the page. No errors, its almost like one of my sql statements is wrong, or it can't connect to my phpMyAdmin database.I'm building a user interface for editing each of the pages, a control panel. I'm running on XAMPP localhost btw, working in dreamweaver. Why is my content not showing up in the form? I know that I am connected to the database.. I've pasted my code from my pages.php and index.php
1. pages.php:
<?php ## Page Manager ?>
<h2>Page Manager</h2>
<div class="col sidebar">
<ul>
<?php
$q = "SELECT * FROM pages ORDER BY name ASC";
$r = mysqli_query($dbc, $q);
if ($r)
{
while($link = mysqli_fetch_assoc($r))
{
echo '<li>'.$link['name'].'</li>';
}
}
?>
</ul>
</div>
<div class="col editor">
<?php if (isset($_GET['id'])) {
$q = "SELECT * FROM pages WHERE id = '$_GET(id)' LIMIT 1";
// the database connection, our query
$r = mysqli_query($dbc, $q);
$opened = mysqli_fetch_assoc($r);
?>
<form action="#" method="post">
<p><label>Page title: </label><input type="text" size="30" name="title" value="<?php echo $opened['title']?>"></p>
<p><label>Page name:</label> <input type="text" size="30" name="name" value="<?php echo $opened['name']?>"></p>
<label>Page body:</label><br>
<textarea name="body" cols="30" rows="8"><?php echo $opened['body'] ?></textarea>
</form>
<?php } ?>
</div>
index.php:
<?php
error_reporting(0);
// Setup document:
include('config/setup.php');
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title><?php //echo $page_title; ?>JakeForDesign - Admin Panel</title>
<link rel="stylesheet" type="text/css" href="css/styles.css">
</head>
<body>
<div class="wrap_overall">
<div class="header"> <?php head(); ?> </div>
<div class="nav_main"> <?php nav_main(); ?> </div>
<div class="content"> <?php include('content/'.$pg.'.php'); ?> </div>
<div class="footer"> <?php footer(); ?> </div>
</div>
</body>
</html>
2. index.php:
<?php
error_reporting(0);
// Setup document:
include('config/setup.php');
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title><?php //echo $page_title; ?>JakeForDesign - Admin Panel</title>
<link rel="stylesheet" type="text/css" href="css/styles.css">
</head>
<body>
<div class="wrap_overall">
<div class="header"> <?php head(); ?> </div>
<div class="nav_main"> <?php nav_main(); ?> </div>
<div class="content"> <?php include('content/'.$pg.'.php'); ?> </div>
<div class="footer"> <?php footer(); ?> </div>
</div>
</body>
</html>
3. setup.php(for connection to database)
<?php
## Setup Document
// host(or location of the database), username, //password, database name
$dbc = #mysqli_connect('localhost', 'root', 'password', 'database') OR die ('Could not connect to the database because: '. mysqli_connect_error() );
include('Functions/sandbox.php');
include('Functions/template.php');
if ($_GET['page'] == '')
{
$pg = 'home';
}
else
{
$pg = $_GET['page'];
}
$page_title = get_page_title($dbc, $pg);
?>
$q = "SELECT * FROM pages WHERE id = '$_GET(id)' LIMIT 1";
This is wrong
$q = "SELECT * FROM pages WHERE id = '" . $_GET['id'] . "' LIMIT 1";
This is good
Don't forget to secure it with intval() if it's a numeric value!
Related
I was trying to make a website. So this is the index.php page.
When 'more info' of any of the form is clicked, the user is redirected to a payment.php page, where the user must make the payment. Once the payment is done, the user is redirected to success.php page, which is supposed to show these 3 lines for two seconds and then redirect the user to details.php page. However, for some reason, instead of redirecting to details.php, both details.php and index.php come up simultaneously like this. How can I avoid the index file from being there too? I just want to show the details file.
Here is the code of the success page:
<?php
include 'index.php';
if(!empty($_GET['tid'] && !empty($_GET['product']))) {
$GET = filter_var_array($_GET, FILTER_SANITIZE_STRING);
$tid = $GET['tid'];
$product = $GET['product'];
} else {
header('Location: payment.php');
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<title>Thank You</title>
</head>
<body>
<div class="container mt-4">
<h2>Thank you for purchasing <?php echo $product; ?></h2>
<hr>
<p>Your transaction ID is <?php echo $tid; ?></p>
<p>Check your email for more info</p>
<?php header('Refresh: 2; URL=details.php?id='.$customer['id']);?>
</div>
</body>
</html>
I feel that this is the most important part of the success.php code:
<?php header('Refresh: 2; URL=details.php?id='.$customer['id']);?>
here's the details page:
<?php
include 'config/db_connect.php';
include 'config/db.php';
include 'index.php';
if (isset($_POST['delete'])) {
$id_to_delete = mysqli_real_escape_string($conn, $_POST['id_to_delete']);
$sql = "DELETE FROM customers WHERE id = $id_to_delete";
if (mysqli_query($conn, $sql)) {
header('Location: index.php');
} else {
echo 'query error: ' . mysqli_error($conn);
}
}
// check GET request id param
if (isset($_GET['id'])) {
// escape sql chars
$id = mysqli_real_escape_string($conn, $_GET['id']);
// make sql
$sql = "SELECT * FROM customers WHERE id = $id";
// get the query result
$result = mysqli_query($conn, $sql);
// fetch result in array format
$customer = mysqli_fetch_assoc($result);
mysqli_free_result($result);
//mysqli_close($conn);
}
?>
<!DOCTYPE html>
<html>
<?php include 'templates/header.php'; ?>
<div class="container center grey-text">
<?php if ($customer) : ?>
<h4><?php echo $customer['Job_Type']; ?></h4>
<p>Contact Number of loan enquirer: <?php echo $customer['Telephone']; ?></p>
<p>Annual income: <?php echo 12 * $customer['Monthly_salary']; ?></p>
<p>Existing loan amount: <?php echo $customer['Existing_loan_amount']; ?></p>
<p>Residential_Type: <?php echo $customer['Residential_Type']; ?></p>
<p>Job: <?php echo $customer['Job']; ?></p>
<p>Form submission time: <?php echo date($customer['Form_Submission_Time']); ?></p>
<!-- DELETE FORM -->
<form action="details.php" method="POST">
<input type="hidden" name="id_to_delete" value="<?php echo $customer['id']; ?>">
<input type="submit" name="delete" value="Delete" class="btn brand z-depth-0">
</form>
<?php else : ?>
<h5>No such customer exists.</h5>
<?php endif ?>
</div>
<?php include 'templates/footer.php'; ?>
</html>
Your details page starts with these three line:
include 'config/db_connect.php';
include 'config/db.php';
include 'index.php';
As you can see, in the third line, you include index.php. My best guess is that that is the reason you see it in the details page.
The list of notes should be displayed within the ul li spans, any reason as to why they aren't showing and instead the array is showing at the top of the page?
The database connection appears to be working perfectly fine, however the notes aren't showing within the spans. It also removes the 'you haven't added any notes text'
code
<?php
require_once 'app/init.php';
$notesQuery = $db->prepare("
SELECT ID, note
FROM notes
");
$notesQuery->execute();
$notes = $notesQuery->rowCount() ? $notesQuery : [];
foreach($notes as $note) {
print_r($note);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Notes</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<header>
<h1>myNotes</h1>
<nav>
Home
About
Contact
</nav>
</header>
<div class="container">
<form action="add.php" method="post">
<textarea name="note" placeholder="Insert a note..." autocomplete="off" required></textarea>
<input type="submit" value="Add" />
</form>
<div class="notes">
<h2>Notes</h2>
<?php if(!empty($notes)): ?>
<ul>
<?php foreach($notes as $note): ?>
<li>
<span><?php echo $note['note']; ?></span>
</li>
<?php endforeach; ?>
</ul>
<?php else: ?>
<p>you haven't added any notes yet.</p>
<?php endif; ?>
</div>
Working Code
<?php
require_once 'app/init.php';
$notesQuery = $db->prepare("
SELECT ID, note
FROM notes
");
$notesQuery->execute();
$notes = $notesQuery->rowCount() ? $notesQuery : [];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Notes</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<header>
<h1>myNotes</h1>
<nav>
Home
About
Contact
</nav>
</header>
<div class="container">
<form action="add.php" method="post">
<textarea name="note" placeholder="Insert a note..." autocomplete="off" required></textarea>
<input type="submit" value="Add" />
</form>
<div class="notes">
<h2>Notes</h2>
<?php if(!empty($notes)): ?>
<ul>
<?php foreach($notes as $note): ?>
<li>
<span><?php echo $note['note']; ?></span>
</li>
<?php endforeach; ?>
</ul>
<?php else: ?>
<p>you haven't added any notes yet.</p>
<?php endif; ?>
</div>
</div>
</body>
</html>
Feel free to use below as an example for your query.
// Your sql query
$sql = "SELECT ID, note FROM notes";
// Prepare your statement
$stmt = $db -> prepare($sql);
// Execute your prepared statement
$stmt -> execute();
// Retreive all rows
$notes = $stmt -> fetchAll();
// Check if array is not empty
if (!empty($notes)) {
//Spit out the array
print_r($notes);
}
I am very new to using PHP.I would like to create a comment box for the user.
1. How do you save the comment in the database
2. How do you see if there are any posts
3. How do you display all posts to current page.
I am using Wampsever/MySQL Workbench. May I have help? Thank you!
<?php
require_once("db_connection.php");
require_once("needed_functions.php");
if (isset($_POST['submit']))
{
//Take Comment
$comment_id = $_POST["comment"];
if ($message == "" )
{
$query = "INSERT INTO comment (";
$query .= "comment";
$query .= ") VALUES (";
$query .= " '{$comment}'";
$query .= ")";
//connect &select
$mysqli = new mysqli("localhost", "user_id");
//query
$result = $mysqli->query("INSERT INTO Comment () VALUES();")
//close
$result->close();
}
}
?>
<!DOCTYPE html>
<html>
<title>JAE Movies</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Poppins">
<style>
body,h1,h2,h3,h4,h5 {font-family: "Poppins", sans-serif}
body {font-size:16px;}
.w3-half img{margin-bottom:-6px;margin-top:16px;opacity:0.8;cursor:pointer}
.w3-half img:hover{opacity:1}
</style>
<body style= "background-image:url(Roll.jpg)">
<!-- Sidebar/menu -->
<nav class="w3-sidebar w3-black w3-collapse w3-top w3-large w3-padding" style="z-index:3;width:300px;font-weight:bold;" id="mySidebar"><br>
Close Menu
<div class="w3-container">
<h3 class="w3-padding-64"><b>JAE<br>Movies</b></h3>
</div>
<div class="w3-bar-block">
Home
Sign In
Sign Up
Information
Customer Service
Administrator
</div>
</nav>
<!-- Top menu on small screens -->
<header class="w3-container w3-top w3-hide-large w3-light-blue w3-xlarge w3-padding">
?
<span>JAE Movies</span>
</header>
<!-- Overlay effect when opening sidebar on small screens -->
<div class="w3-overlay w3-hide-large" onclick="w3_close()" style="cursor:pointer" title="close side menu" id="myOverlay"></div>
<!--Start Inserting Page Content-->
<div class="w3-main" style="margin-left:340px;margin-right:40px">
<!-- Header -->
<div class="w3-container" style="margin-top:80px" id="userhome">
<h1 class="w3-jumbo w3-text-white"><b>Lion King</b></h1>
</div>
<!--Image-->
<div class="w3-half">
<img src="Images/LionKing.jpg" alt="LionKing" style="width:100%">
</div>
<!--Description-->
<div class="w3-half">
<p style="color:white";>Lion cub and future king Simba searches for his identity. His eagerness to please others and penchant for testing his boundaries sometimes gets him into trouble.</p></br>
</div>
<!--Buttons-->
<div>
<button type="submit">WATCH TRAILER!</button>
<button type="submit">WATCH MOVIE</button>
</div>
<!--Comments-->
<div>
<br>
<textarea rows="4" cols="50" name="comment" form="usrform">
Enter comment here...</textarea>
<form action=" " method="post" id="com">
<input type ="submit" name="submit" value="submit" class="texty" >
</form>
</div>
When using database connections in PHP make sure you do the following
//connect &select
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
//query
$result = $mysqli->query("INSERT INTO tbl_name () VALUES();") // Add the update comment here
//close
$result->close();
Always remember to :
connect
select
query
close
you'll then need to get all of the comments for the page using the same process but with the select process rather than insert.
<?php
require_once("db_connection.php");
require_once("needed_functions.php");
if(isset($_POST['submit'])){
$comment = mysql_escape_string($_POST['comment']);
$sql = "INSERT INTO comments (comment) VALUES ('$comment')";
if($res = $link->query($sql)){
}
else
{
echo "Error".$sql."<br>".$link->error;
}
}
?>
<!DOCTYPE html>
<html>
<title>Movies</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Poppins">
<style>
body,h1,h2,h3,h4,h5 {font-family: "Poppins", sans-serif}
body {font-size:16px;}
.w3-half img{margin-bottom:-6px;margin-top:16px;opacity:0.8;cursor:pointer}
.w3-half img:hover{opacity:1}
</style>
<body>
<div class="container">
<img src="images/1.jpg" alt="loinKing" style="width:100%;height:300px;">
<br>
<br>
<form action="" method="post">
<div class="form-group">
<textarea type="text" name="comment" placeholder="Type Comment.." class="form-control"></textarea>
</div>
<div class="form-group">
<input type="submit" name="submit" value="POST" class="btn btn-primary">
</div>
</form>
<!-- Left-aligned -->
<?php
//HERE SHOW OR DISPLAY THE COMMENTS
$q = "SELECT * FROM comments ORDER BY id DESC";
if($r->num_rows > 0){
while($row = $r->fetch_assoc()){
?>
<div class="media">
<div class="media-left">
<img src="images/img_avatar1.png" class="media-object" style="width:60px">
</div>
<div class="media-body">
<p>Date Posted : <?php echo $row['date'];?></p>
<p>Comments :<?php echo $row['comment'];?></p>
</div>
</div>
<?php
}
}
else
{
?>
<h4>No Comments Available</h4>
<?php
}
}
else
{
echo "Error".$sql."<br>".$link->error;
}
?>
</div>
</body>
So their is a code which save comment in database , displays in database and if comment is not posted or not available than it show NO COMMENT AVAILABE message.
I'M USING PHP AND MYSQLI HERE. Recommend not to use mysql as it is deprecated.
THE DATABASE TABLE IMAGE
CODE OUTPUT IMAGE
php file:
<?php
$link = new mysqli ('localhost','root','admin','demo1');
if($link->connect_error){
die ("Connection failed".$link->error);
}
if(isset($_POST['submit'])){
$comment = mysql_escape_string($_POST['comment']);
$sql = "INSERT INTO comments (comment) VALUES ('$comment')";
if($res = $link->query($sql)){
}
else
{
echo "Error".$sql."<br>".$link->error;
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>PHP</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<img src="images/1.jpg" alt="loinKing" style="width:100%;height:300px;">
<br>
<br>
<form action="" method="post">
<div class="form-group">
<textarea type="text" name="comment" placeholder="Type Comment.." class="form-control"></textarea>
</div>
<div class="form-group">
<input type="submit" name="submit" value="POST" class="btn btn-primary">
</div>
</form>
<!-- Left-aligned -->
<?php
//HERE SHOW OR DISPLAY THE COMMENTS
$q = "SELECT * FROM comments ORDER BY id DESC";
if($r = $link->query($q)){
if($r->num_rows > 0){
while($row = $r->fetch_assoc()){
?>
<div class="media">
<div class="media-left">
<img src="images/img_avatar1.png" class="media-object" style="width:60px">
</div>
<div class="media-body">
<p>Date Posted : <?php echo $row['date'];?></p>
<p>Comments :<?php echo $row['comment'];?></p>
</div>
</div>
<?php
}
}
else
{
?>
<h4>No Comments Available</h4>
<?php
}
}
else
{
echo "Error".$sql."<br>".$link->error;
}
?>
</div>
</body>
</html>
I hope all of your questions are answered. If not then reply to me....
Error For some reason I'm not finding:
Your screenshot is exactly what I am looking
I am building a web page which has many albums. It will be displaying images when I click one of the albums.
ISSUE 1: The problem I am having now is that all images from different albums will be displayed when I click into only one of the album.
ISSUE 2: In the php file that is for after clicking the album. I want to display only one picture for only one product but my code seems not working correctly
t1.recordid = t2.categoryrecordid
t2.productrecordid = t3.productid
The structure of my MySQL table design:
Category:
Product:
Productimage:
The code for my album:
<div class="row">
<?php
$stmt = $DB_con->prepare('SELECT recordid, catcode,title,imgfile,catdesc FROM category ORDER BY recordid DESC');
$stmt->execute();
if ($stmt->rowCount() > 0) {
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
extract($row);
?>
<div class="col-xs-3">
<p><img src="./images/<?php echo $row['catcode']?>/<?php echo $row['imgfile']; ?>" class="img-rounded" width="190px" height="160px" /></p>
<p><a class="page-header" href="collectionGallery.php?cat= <?php echo $row['catcode']; ?>"><?php echo $row['title']; ?></a></p> <br/>
</div>
<?php
}
} else {
?>
<div class="col-xs-12">
<div class="alert alert-warning">
<span class="glyphicon glyphicon-info-sign"></span> No Data Found ...
</div>
</div>
<?php
}
?>
</div>
</div>
The code for after I clicking to album(display images of that album):
<div class="row">
<?php
$stmt = $DB_con->prepare('SELECT category.*, product.*, productimage.* FROM category JOIN product ON product.categoryrecordid=category.recordid JOIN productimage ON productimage.productid=product.productrecordid');
$stmt->execute();
if ($stmt->rowCount() > 0) {
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
extract($row);
?>
<div class="col-xs-3">
<p><img src="./images/<?php echo $row['catcode'].'/'. $row['imagefilename']; ?>" class="img-rounded" width="190px" height="160px" /></p>
<p><?php echo $row['productcode'].' Price:'.$row['price']; ?></a></p>
</div>
<?php
}
} else {
?>
<div class="col-xs-12">
<div class="alert alert-warning">
<span class="glyphicon glyphicon-info-sign"></span> No Data Found ...
</div>
</div>
<?php
}
?>
</div>
So There is a similar example of the code Which can help you to understand.
but this is in Mysqli Object oriented as i myself learning PDO. But i'm sure this will give to preety good understanding .
Here i'm using PHP Object oriented with Mysqli prepared Statement
1) Create a table in database with name : albums
2) Create a table in database with name : productimg
3) INDEX PAGE: index.php
<?php
include('products.php');
$newprod = new products();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>PHP MYSQL SHOW ALBUMS</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<ul class="breadcrumb" style="width:100px;">
<li>d</li>
<li>d</li>
<li>d</li>
</ul>
<div class="row">
<?php $newprod->showAlbums(); ?>
</div>
</div>
</body>
</html>
4)this file displays album and product image : products.php
<?php
class products{
private $link;
function __construct(){
$this->link = new mysqli('localhost','root','admin','codexworld');
if(mysqli_connect_errno()){
die("connection failed".mysqli_connect_errno());
}
}
function showAlbums(){
$sql = $this->link->stmt_init();
if($sql->prepare("SELECT pname,album_name,product_code FROM albums")){
$sql->bind_result($pname,$albumname,$pcode);
$sql->execute();
while($sql->fetch()){
?>
<div class="col-md-4">
<a href="displproduct.php?pcode=<?php echo $pcode;?>"><img src="albumimages/<?php echo $albumname;?>" alt="<?php echo $pname; ?>" class="" style="width:200px;height:200px;">
<h4>ALBUM :<strong><?php echo $pname;?></strong></h4></a>
</div>
<?php
}
}
}
function showproducts($productcode){
$sql = $this->link->stmt_init();
if($sql->prepare("SELECT productname,productid,image FROM productimg WHERE productid = ?")){
$sql->bind_param('s',$productcode);
$sql->bind_result($pname,$pid,$img);
$sql->execute();
while($sql->fetch()){
?>
<div class="col-md-4">
<img src="productimg/<?php echo $img;?>" alt="<?php echo $pname; ?>" class="" style="width:200px;height:200px;">
<h4>Product Image :<strong><?php echo $pname;?></strong></h4>
</div>
<?php
}
}
}
}
?>
5)This file displays products : displproduct.php
<?php
include('products.php');
$newprod = new products();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>PHP MYSQL SHOW ALBUMS</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<?php if(isset($_GET['pcode'])){
$productcode = $_GET['pcode'];
$newprod->showproducts($productcode);
}
?>
</div>
</div>
</body>
</html>
I have some code which attempts to check whether a user is an admin or customer to login, and then there's one problem I can't solved it. When I use the customer user's account to login, for example using redhood as my customer's username to access the customer login page. But when I use the admin user's account to login, for example using wolfpack as my admin's username, it redirect me to the customer login page instead of the admin login page. But I don't know which php code I need to change. Can anyone solve this problem? Thanks!
MySql Database:
Signin.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/signin/signin_desktop.css">
<link rel="stylesheet" type="text/css" href="css/signin/signin_tablet.css" media="screen and (max-width:768px)">
<link rel="stylesheet" type="text/css" href="css/signin/signin_mobile.css" media="screen and (max-width:480px)">
</head>
<body>
<div id="wrapper">
<header>
<nav id="mainMenu">
<img src="logo/logo.png" id="logo">
<ul>
<li>Home</li>
<li>About</li>
<li>Booking Rates</li>
<li>Recreation</li>
</ul>
</nav>
</header>
<section id="banner">
<div id="ritu" class="shadow">
<img src="images/content_pure.jpg">
<img src="images/Sports-Hub-Gym.jpg">
<img src="images/gym.jpg">
<img src="images/ClubFitt2jpg.jpg">
</div>
</section>
<section id="content">
<div id="sign">
<div class="user">
<h2>Existing User</h2>
<form action="checkuser.php" method="post">
<p style="color:white;">Username:</p>
<input type="text" name="uname" size="25" maxlength="20" placeholder="Please enter your username" required><br><br>
<p style="color:white;">Password:</p>
<input type="password" name="pword" size="25" maxlength="20" placeholder="Please enter your password" pattern=".{6,}" required><br><br>
<input type="submit" name="loginbtn" value="">
</form>
<?php
if(isset($_GET['uname']) && isset($_GET['pword']))
{
echo "<script>alert('Invalid Username and Password.')</script>";
}
?>
</div>
<div class="user">
<h2>New User</h2>
<img id="create" src="button/CREATE%20ACCOUNT.png">
<p style="color:white;">Ads:</p>
<div id="ads">
<div class="row">
<div class="image">
<img id="minilogo" src="logo/logo.png">
<div id="advt">
Download Now
</div>
</div>
<div class="image">
<img id="apps" src="images/myActiveSG%20APP.jpg">
</div>
</div>
</div>
</div>
</div>
</section>
<footer>
<p>© Copyright 2016 SportLab. All Rights Reserved.</p>
<nav id="submenu">
<ul>
<li>Sitemap | </li>
<li> Contact |</li>
<li>Term of Use </li>
<li>| Privacy </li>
</ul>
</nav>
</footer>
</div>
</body>
</html>
PHP
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Check Login</title>
</head>
<body>
<?php
if(isset($_POST["loginbtn"]))
{
$u=$_POST['uname'];
$p=$_POST['pword'];
$conn=mysqli_connect("localhost", "root", "" , "M3_156020K_Syahri_SportFacility");
$sql = "SELECT * FROM create_user WHERE username='" .$u. "' AND password='" .$p. "' ";
$search_result=mysqli_query($conn, $sql);
$userfound=mysqli_num_rows($search_result);
if($userfound >= 1)
{
session_start();
$_SESSION['MM_Username']= $u;
$row=mysql_fetch_assoc($search_result);
if($row['role'] == 1)
{
header("Location: login_admin.html");
}
else
{
header("Location: login_cust.html");
}
}
else
{
header("Location: signin.html?uname=" . $u . "&pword=" . $p);
}
mysqli_close($conn);
}
?>
At a quick glance, one of the things you should correct, is to not send output until AFTER you have finished working with the session. Also, as Rafael mentioned, you are checking if the field equals 1, and not the actual value in the field.
For example, moving the html block to after your conditions like so ( Updated this example to use prepared statements ) :
<?php
if(isset($_POST["loginbtn"])) {
$u=$_POST['uname'];
$p=$_POST['pword'];
$conn=new mysqli("localhost", "root", "" , "M3_156020K_Syahri_SportFacility");
$sql = "SELECT `role` FROM create_user WHERE username=? AND password=?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('ss', $u, $p);
$stmt->execute();
$stmt->bind_result($role);
$stmt->close();
$conn->close();
if($role) {
session_start();
$_SESSION['MM_Username']= $u;
if($role == 'Admin') {
header("Location: login_admin.html");
} else {
header("Location: login_cust.html");
}
} else {
header("Location: signin.html?uname=" . $u . "&pword=" . $p);
}
mysqli_close($conn);
}
?><!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Check Login</title>
</head>
<body>
At the end of the day, I would seriously reconsider writing your own login system from scratch especially given the apparent lack of attention to obvious security holes. I would recommend a package out of the box such as otp-thing or if you must write the whole portal yourself, something like Laravel/etc.
Aside from the security issues in the code others have stated, to answer your question...your condition is wrong:
if($row['role'] == 1) should be changed to if ($row['role'] == "Admin")
In your case the role is never 1 and therefore will always hit the else condition sending them to login_cust.html.
Your database roles are only User and Admin. Change the condition.