Setting $_SESSION as result from MySQL Query - php

I'm trying to create a script that logs you in and creates a session using a set usercode in the same table as my usernames.
Each usercode is different to each username as each usercode will display different data on my index.php
I am using the following code to authenticate my users and assign their usercodes:
<?php
include ("include/dbConfig.php");
$tbl_name="users"; // Table name
// Connect to server and select databse.
mysql_connect($db_hostname, $db_username, $db_password)or die("cannot connect"); // no quotes needed around vars
mysql_select_db($db_database)or die("cannot select DB"); // no quotes needed around vars
$username = mysql_real_escape_string($_POST['username']);
$encrypted_password = mysql_real_escape_string(md5($_POST['password']));
$sql="SELECT username, password FROM $tbl_name WHERE username='$username' and password='$encrypted_password'";
$sql2="SELECT usercode FROM $tbl_name WHERE usercode='$usercode'";
$result=mysql_query($sql);
$result2=mysql_query($sql2);
$sql2= $usercode1['usercode'];
// If result matched $username and $password, table row must be *AT LEAST* 1 row
if(mysql_num_rows($result)){
session_start();
$_SESSION['isamsdata']->UserCode) != ''; //This needs fixing - array
header("Location: index.php?logged in successfully");
} else {
header("Location:login.php?msg=email or password wrong");
}
?>
My index.php:
<?php
error_reporting(E_ALL);
session_start();
//$_SESSION['isamsdata']->UserCode = 'test';
unset($_SESSION['child_id']);
unset($_SESSION['child_first_name']);
require_once('include/newuserfunction.php');
if (isset($_SESSION['isamsdata']) AND $_SESSION['isamsdata'] != '') {
include "header.php";
include "topmenu.php";
include "leftmenu.php";
?>
<?php
include 'helpBox.php';
?>
<!-- BEGIN PAGE -->
<div class="page-content">
<!-- BEGIN PAGE CONTAINER-->
<div class="container-fluid">
<!-- BEGIN PAGE HEADER-->
<div class="row-fluid">
<div class="span12">
<!-- BEGIN PAGE TITLE & BREADCRUMB-->
<h3 class="page-title">
Parent Dashboard
<small>This is your dashboard.</small>
<button class="btn orange" style="float: right; width: 150px;" id="addpupil" onclick="showhidepupilbox();" >Add Pupil</button>
</h3>
<ul class="breadcrumb">
<li>
<i class="icon-home"></i>
Home
<i class="icon-angle-right"></i>
</li>
<li>Dashboard</li>
<!--<button style="float: right; background-color:green; color: white !important; margin: -1px 9px 0px 0px; border: none;" onclick="addChild();">Add Child</button>-->
</ul>
<!-- END PAGE TITLE & BREADCRUMB-->
</div>
</div>
<?php
if(isset($_GET['status']))
{
if($_GET['status'] == 1) {
echo '<div class="alert alert-success">
<button class="close" data-dismiss="alert"></button>Pupil Added Successfully. </div>';
} else {
echo '<div class="alert alert-error">
<button class="close" data-dismiss="alert"></button>Pupil Not Added Successfully. </div>';
}
}
?>
<div class="row-fluid" id="addpupilform" style="display: none;" >
<div class="span12">
<div class="portlet box orange-steel">
<div class="portlet-title">
<h4><i class="icon-table"></i>Add Pupil</h4>
</div>
<div class="portlet-body">
<div class="portlet-body form">
<form action="insert-child.php" id="add_user" class="form-horizontal add_user" method="post" name="childform">
<div class="alert alert-error hide">
<button class="close" data-dismiss="alert"></button>
You have some form errors. Please check below. </div>
<div class="alert alert-success hide">
<button class="close" data-dismiss="alert"></button>
Your form validation is successful! </div>
<div class="control-group">
<label class="control-label">First Name<span class="required">*</span></label>
<div class="controls">
<input type="text" maxlength="15" name="first_name" data-required="1" class="span6 inputfields m-wrap popovers field_autosave required" />
</div>
</div>
<div class="control-group">
<label class="control-label">Last Name<span class="required">*</span></label>
<div class="controls">
<input type="text" maxlength="15" name="last_name" data-required="1" class="span6 inputfields m-wrap popovers field_autosave required" />
</div>
</div>
<div class="control-group">
<label class="control-label">Date Of Birth<span class="required">*</span></label>
<div class="controls">
<input type="text" maxlength="15" name="dob" data-required="1" class="span6 inputfields m-wrap popovers field_autosave required" />
</div>
</div>
<div class="form-actions" style=" padding-left: 12px;">
<button type="submit" class="btn orange" >Add</button>
</div>
</form>
<!--- close body-form-->
</div>
</div>
</div>
</div>
</div>
<div class="row-fluid">
<div class="span12">
<div class="clearfix"></div>
<div class="rows">
<div class="span12">
<div class="portlet box orange-steel">
<div class="portlet-title">
<h4><i class="icon-table"></i>Pupil's Details</h4>
</div>
<div class="portlet-body">
<!--<div class="scroller" style="height: 300px;" data-always-visible="1" data-rail-visible="0">-->
<div class="portlet-body">
<?php if(getUserChilds($_SESSION['isamsdata']->UserCode) != '') { ?>
<table class="table table-striped table-bordered table-hover" id="sample_2">
<thead>
<tr>
<th >First Name</th>
<th>Last Name</th>
<th>Date Of Birth</th>
<th>Change Details</th>
<th>Progress</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
echo getUserChilds($_SESSION['isamsdata']->UserCode);
?>
</tbody>
</table>
<?php } else { ?>You have not setup any pupil account currently, please fill the form by clicking the Add Pupil icon above.<?php } ?>
</div>
</div>
<!-- scroller </div>-->
</div>
</div>
<!-- End Rows-->
</div>
<!-- Close Div span12-->
</div>
<!-- Close Row-span12 -->
</div>
<!-- Close Row-fluid -->
<div class="row-fluid">
<div class="span12">
<div class="clearfix"></div>
<div class="rows">
<div class="span12">
<div class="portlet box orange-steel">
<div class="portlet-title">
<h4><i class="icon-table"></i>Welcome Parent</h4>
</div>
<div class="portlet-body">
<!--<div class="scroller" style="height: 300px;" data-always-visible="1" data-rail-visible="0">-->
<div class="portlet-body">
Dear <i><?php echo $_SESSION['parentdetails']->title;?> <?php echo $_SESSION['parentdetails']->firstName;?> <?php echo $_SESSION['parentdetails']->surname;?>,</i><br><br>
<p>
A very warm welcome to the on-line joining forms and thank you so much for logging on. We know there's a lot to do here but we hope that completing these on-line forms will be relatively easy and stress-free. Simply enter the name of your son or daughter above by clicking on the ‘add pupil’ tab at the top right hand corner of this page and then click ‘Fill form’.
</p>
<p>
The fields which contain a red asterisk symbol must be completed. All updates to the forms are automatically saved so you can return to the on-line joining forms at any time to complete your submissions.
</p><p>
We recommend that you have a copy of the new parents' Joining Booklet in front of you whilst completing these forms. Don't worry if you haven't, because you can access a PDF of the Joining Booklet 2014 here. Information and help icons are available on all the forms in case you need guidance and, if you are still stuck, please do not hesitate to call the Admissions Office on 000000000.
</p><p>
As well as the forms, we would be very grateful if you could upload a picture of your son/daughter when prompted (this does not have to be a passport photo) and also a copy of the main page of your son or daughter's passport with all their details on it. If you do not have access to a scanner, then please feel free to send in a photocopy to Name, Registrar, at the usual School/College address.
</p><p>
I should also remind you that we do require the following to be posted in hard-copy back to the School/College:</p><p>
<ul style="width: 80%;">
<li>The Medical Forms (required) <a class="pull-right" href="#" target="_blank">Download Form</a></li>
<li>The Direct Debit Form (if appropriate) <a class="pull-right" href="#" target="_blank">Download Form</a></li>
<li>The Gift Aid Form (if appropriate) <a class="pull-right" href="#" target="_blank">Download Form</a></li>
</ul></p><p>
All forms should be completed by Monday 16th June. The information provided on these forms will be processed lawfully and fairly and held for our management and administrative purposes only.
</p><p>
I do hope that you all remain as excited about September as we are, and we look forward to seeing you all soon.
</p><p>
With best wishes,
</p><p>
Name here<br>
Director of Admissions
</p> </div>
</div>
<!-- scroller </div>-->
</div>
</div>
<!-- End Rows-->
</div>
<!-- Close Div span12-->
</div>
<!-- Close Row-span12 -->
</div>
<!-- Close Row-fluid -->
</div>
</div>
<!-- END PAGE CONTAINER-->
</div>
<!-- END PAGE CONTAINER-->
</div> <!-- END PAGE -->
<?php
include "footer.php";
} else {
header("Location:login.php");
}
?>
<script>
function showhidepupilbox()
{
console.log('Check');
jQuery('#addpupilform').toggle();
}
jQuery(document).ready(function() {
jQuery('#addpupilform').hide();
jQuery('#addpupil').click(function(){
console.log('sdf');
jQuery('#addpupilform').toggle();
});
App.setPage("table_managed"); // set current page
App.init(); // init the rest of plugins and elements
});
jQuery(document).ready(function() {
App.setPage("form_validation"); // set current page
App.init(); // init the rest of plugins and elements
});
jQuery(document).ready(function() {
});
</script>
<!-- END JAVASCRIPTS -->
</body>
<!-- END BODY -->
</html>
I'm quite new to PHP and SQL so any corrections would be respected!
If any database structures are needed, please ask.

What can be improved / needs fixing:
You are using mysql_, which is depreciated since php 5.5 and shouldn't be used any more. Since you are new to php, now is the right time to learn PDO or mysqli_!
You are using md5, which shouldn't be used any more.
And:
session_start();
needs to be the first line in all files that make use of session.
I guess you are using a tutorial that you have found - which is the right way, but I recommend finding another one.
I haven't fixed the md5 issue, because your passwords need to be changed in DB and the script wouldn't work if I did - but change it to mcrypt
I wrote a comment in the code - variable $usercode isn't set, I don't know where it's comming from, you might want to include usercode in the first query/do both together.
Here is your file writen with PDO:
<?php
session_start();
include('include/.db_def.php');
try {
$connection = new PDO('mysql:host=' . HOST_ONE . ';dbname=' . DB_ONE , USER_ONE, PASS_ONE);
$state = $connection->prepare("SELECT username, password FROM users WHERE username = :names AND password = :password");
$state->execute(array('names' => $_POST['username'], 'password' => md5($_POST['password'])));
list ($user,$password)=$state->fetch(PDO::FETCH_NUM);
$state->closeCursor();
$state2 = $connection->prepare("SELECT usercode FROM users WHERE usercode= :usercode");
$state2->execute(array('usercode' => $usercode)); //<<< $usercode isn't set, you need to fix this
list($usercode)=$state2->fetch(PDO::FETCH_NUM);
$state2->closeCursor();
unset($connection);
if (isset($usercode) AND $usercode != '')
{
$_SESSION['isamsdata'] = $usercode;
header("Location: index.php?logged in successfully");
exit();
}
else {
header("Location:login.php?msg=email or password wrong");
exit();
}
} catch (PDOException $e) {
die('Error!: ' . $e->getMessage() . '<br/>');
}
Your .db_def.php should look like this:
define('HOST_ONE','your host');
define('USER_ONE','db_user');
define('PASS_ONE','db_pass');
define('DB_ONE','db');
SIDENOTE:
I suppose usercode is in the users table? If so, change the query to:
$state = $connection->prepare("SELECT username, password, usercode FROM users WHERE username = :names AND password = :password");
and the part after list to:
list ($user,$password,$usercode)=$state->fetch(PDO::FETCH_NUM);
You can then get rid of the second query!
Here is the complete code with only one query:
<?php
session_start();
include('include/.db_def.php');
try {
$connection = new PDO('mysql:host=' . HOST_ONE . ';dbname=' . DB_ONE , USER_ONE, PASS_ONE);
$state = $connection->prepare("SELECT username, password, usercode FROM users WHERE username = :names AND password = :password");
$state->execute(array('names' => $_POST['username'], 'password' => md5($_POST['password'])));
list ($user,$password,$usercode)=$state->fetch(PDO::FETCH_NUM);
$state->closeCursor();
unset($state,$connection);
if (isset($usercode) AND $usercode != '')
{
$_SESSION['isamsdata'] = $usercode;
header("Location: logged_in.php?logged in successfully");
exit();
}
else {
header("Location:login.php?msg=email or password wrong");
exit();
}
} catch (PDOException $e) {
die('Error!: ' . $e->getMessage() . '<br/>');
}
?>
Your next pages should start like this:
<?php
session_start();
if (isset($_SESSION['isamsdata']) AND $_SESSION['isamsdata'] != '') {
// user seems to be logged in, do whatever you want here
}
else
{
header("Location:login.php?msg=you_are_not_logged_in");
exit();
}
File structure I would recommend:
Create a folder "views"
in views, put this .htaccess file:
<Files ~ "\.(htaccess|php)$">
order allow,deny
deny from all
</Files>
in your root folder, put the file I wrote above and name it index.php, and create the following file for every file you want to run, for the start, name it logged_in:
<?php
session_start();
if (isset($_SESSION['isamsdata']) AND $_SESSION['isamsdata'] != '') {
include('views/logged_in.php'); //here you put the file you want to run
}
else
{
header("Location:login.php?msg=not_logged_in");
exit();
}
Now, all the files you want to run will have to be in the 'views' folder, but you allways link to the file in your root folder. You need to create two files with the same name(makes it easier), one in root, one in views. In root, the file should contain the line
include('views/index.php');
but changed to the file you want to run, f.e.
include('views/dashboard.php');
Now create the file logged_in.php in "views" and just put
<?= "HELLO"; ?>
into it, just to see if it's running.

$sql2="SELECT usercode FROM $tbl_name WHERE usercode='$usercode'"
Variable $usercode is undefined
$sql2= $usercode1['usercode'];
Variable $usercode1 is undefined and code is very strange
$_SESSION['isamsdata']->UserCode) != '';
This code is strange. If you want compare it then you should use operator if
I recommended you turn full error reporting and turn on errors output. You can make this by PHP settings in php.ini or in your code.
For example in begin of script
error_reporting(E_ALL);
ini_set("display_errors", 1);

You can do like follwing code:
<?php
session_start();
include ("include/dbConfig.php");
$tbl_name="users"; // Table name
// Connect to server and select databse.
mysql_connect($db_hostname, $db_username, $db_password)or die("cannot connect"); // no quotes needed around vars
mysql_select_db($db_database)or die("cannot select DB"); // no quotes needed around vars
$username = mysql_real_escape_string($_POST['username']);
$encrypted_password = mysql_real_escape_string(md5($_POST['password']));
$sql="SELECT usercode FROM $tbl_name WHERE username='$username' and password='$encrypted_password'";
$result=mysql_query($sql);
// If result matched $username and $password, table row must be *AT LEAST* 1 row
if(mysql_num_rows($result)){
$row = mysql_fetch_assoc($result);
$usercode= $row['usercode'];
if($usercode!=''){
$_SESSION['isamsdata']->UserCode= $usercode;
header("Location: index.php?logged in successfully");
} else {
header("Location:login.php?msg=email or password wrong");
}
}
?>

Related

How can I send Passport number in url through button?

I Just want to send passport number in the url on the next page. I know it will go into the url like this continue-to-pay.php?pno=$passportnumber".
But how will I post passport number on the next page.
<?php
include'connection.php';
$pno=$_GET['pno'];
$sql="SELECT * FROM user WHERE passportnumber='$pno'";
$query = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($query))
{
?>
<div class="col-xs-6 col-sm-6 col-md-6 col-lg-5 text-right" id="review">
<ul>
<li class="list">Passport Number </li>
</ul>
</div>
<div id="review2">
<ul>
<li class="list"><?php echo $row['passportnumber']; ?></li>
</ul>
</div>
<br><br>
<div class="col-xs-6 col-sm-12 col-md-12 col-lg-12" align="center"
valign="top">
<a href="e-visa-application.php?actionType=edit" class="btn btn-primary
btn-lg mgn-btm mgn-top ">Edit</a>
<a href="process.php" class="btn btn-primary btn-lg mgn-btm mgn-top
">Continue to pay</a>
</div>
if you got the PNO at your URL you can get it in a PHP file using $_GET :
<?php
if (isset($_GET['pno'])) {
echo $_GET['pno'];
}else{
// Fallback behaviour goes here
}
?>
You are probably searching for "The PHP session system" to keep the pno in the session while the user is going through the steps.
The PHP session system lets you store securely data in the $_SESSION global array. A example is to store the pno in the session.
session_start();
$_SESSION['pno'] = $pno;
Then, you can access that information on all other pages:
if (isset($_SESSION['pno']))
echo $_SESSION['pno'];
More info about sessions here
You can use $_REQUEST:
<?php
$_REQUEST['pno'] = $pno;
?>
you can use it to retrieve the pno in the continue-to-pay.php?pno=$passportnumber

Unknown issue with $_SERVER["REQUEST_METHOD"] returning false when it should be true

Hey there stackoverflow users, i have come upon a very confusing problem that I cant seem to move past. I am creating a forum type web page and am currently working on the comments section. I have a form that uses the post method to send your comment as well as a hidden input to store the threads ID. I will post the entire php file below just to make sure nothing is left out.
<?php
session_start();
parse_str($_SERVER['QUERY_STRING'], $link);
$threadID = $link['ID'];
require("config.php");
$connection = mysqli_connect($host, $user, $password, $database);
$error = mysqli_connect_error();
if($error != null) {
$output = "<p>Unable to connect to database!</p>";
exit($output);
} else {
//Get Thread Data
$query = "SELECT username, title, content FROM threads, users WHERE threads.ID = $threadID AND users.ID = threads.makerID;";
$results = mysqli_query($connection, $query);
$row = mysqli_fetch_assoc($results);
//Get Comment Data
$query = "SELECT username, comment FROM comments, users WHERE threadID = $threadID AND users.ID = comments.makerID;";
$results = mysqli_query($connection, $query);
$row = mysqli_fetch_assoc($results);
}
?>
<!DOCTYPE html>
<html>
<head lang="en">
<title>BodyweightMate</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="../css/styling.css"/>
</head>
<body>
<!--Top masthead-->
<header class="masthead" id="top">
<h1 class="masthead-title"> Welcome To BodyweightMate </h1>
</header>
<!--Navigation bar-->
<nav class="navbar">
<table class="navbar-table">
<tr>
<!--Logo-->
<td>
<a class="navbar-brand" href="main.php">
<img src="../images/logo.jpg" alt="BodyweightMate" height="30" width="30">
</a>
</td>
<!--Login/Profile-->
<?php if(isset($_SESSION['login_user'])) {
echo"<td><a class=\"navbar-profile\" href=\"profile.php\"> Profile </a></td>";
echo"<td><a class=\"navbar-logout\" href=\"logout.php\"> Logout </a></td>";
} else {
echo"<td><a class=\"navbar-login\" href=\"login.php\"> Login </a></td>";
}?>
</tr>
</table>
</nav>
<!--Main portion-->
<section class="content-section">
<article>
<h3><?php echo $row['username']. ": " .$row['title']; ?></h3>
<p><?php echo $row['content']; ?></p>
<br>
<h3>Comments</h3>
<p>Some annoying user: Gr8 B8 M8</p>
<p>Annoying users friend: I R8 8/8</p>
</article>
<div>
<!--If logged in, ability to comment-->
<?php if(isset($_SESSION['login_user'])): ?>
<form role="comment-form" method="POST" action="processcomment.php" id="mainForm">
<input type="hidden" value="$threadID" name="threadID">
<div class="form-group">
<label for="comment">Comment </label> <br>
<textarea class="comment-text" name="comment" rows="2" maxlength="255"></textarea>
</div> <br>
<input type="Submit" class="btn-newcomment" value="Submit Comment" name="submit">
</form>
<?php endif ?>
</div>
</section>
<!--Right portion-->
<aside class="content-aside">
<div>
<!--If logged in, be able to create a thread-->
<?php
if(isset($_SESSION['login_user'])) {
echo"<form method=\"post\" action=\"makethread.php\">";
echo"<input type=\"submit\" class=\"btn-newthread\" value=\"Create New Thread\" name=\"submit\">";
echo"</form>";
}
?>
</div>
<!--Info-->
<div>
<p> GOING TO NEED A SEARCH FUNCTION HERE
This is the cool little aside section. It will always be there to provide you with some very nice little details, helpful links, maybe a list of moderators? who knows! The uses are endless when you have a beautiful little aside like this one! Here are a few very useful bodyweight fitness links to get us started :D </p>
</div>
<br>
<div>
<ul class="content-aside-links">
<li>
Reddit's Bodyweightfitness Forum
</li>
<li>
Reddit's Bodyweightfitness RR
</li>
<li>
Antranik's Bodyweightfitness Routine
</li>
</ul>
</div>
<div></div>
</aside>
<!--Footer -->
<footer class="footer">
<div>
<p> Use of this site constitutes acceptance of our User Agreement © 2017 BodyweightMate inc. All rights reserved. </p>
</div>
</footer>
</body>
</html>
The error is occurring under the main portion where i check if a user is logged in, and if they are add a short form consisting of a message, a text area, and a submit button. This form sends the information to the following php file.
<?php
session_start();
if(!isset($_SESSION['login_user'])) { header("location: main.php"); }
?>
<!DOCTYPE html>
<html>
<body>
<?php
require("config.php");
$connection = mysqli_connect($host, $user, $password, $database);
$error = mysqli_connect_error();
if($error != null) {
$output = "<p>Unable to connect to database!</p>";
exit($output);
} else {
//Validation
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$comment = $_POST['comment'];
$threadID = $_POST['threadID'];
$user = $_SESSION['login_user'];
} else {
//Redirect back to register
echo"<p>Form must use post or input was bypassed.</p>";
echo" Return to home page. ";
mysqli_close($connection);
exit();
}
There is no issue with connecting to the database, and I don't believe the remainder of the code is necessary to help me with this error since that one if statement of checking if the form is using post is failing and the else statement is always called. Why is this? i have rewritten the form multiple times ensuring that its properly structured and using post yet it fails every time!

how to create a jquery mobile listview from displaying data from mysql database using php

I am creating a web app that should insert jobs into the database for logged in users, after you click a job on the listview,a page is displayed showing the jobs,city,details then you have two buttons,apply and favorites,apply works just fine,favorites insert the selected job into a table and write it to another page "favorite" in a listview using php,It does write it but all the job selected by a specific user as favorite appear on a single listview block and i also want to create a link to the job file that specify all the details about that job.
Here are my Jquery and my PHP codes
<div data-role="page" id="page6" data-add-back-btn="true">
<div data-role="header">
<h1>Favorites</h1>
</div>
<div data-role="content">
<?php
if(isset($_POST['submit'])){
move_uploaded_file($_FILES['file']['tmp_name'],"picture-upload/".$_FILES['file']['name']);
$con=mysqli_connect("localhost","root","","recruitment");
$q=mysqli_query($con,"UPDATE users SET image='".$_FILES['file']['name']."'where username='".$_SESSION['username']."'");
}
?>
<form action="index.php" method="post" enctype="multipart/form-data" data-ajax="false">
<h5><span>
<div id="box1">
<input name="file" id="file" class="hidden" type="file" ><br>
<button type="submit" class="btn btn-primary" name="submit" data-role="none">Upload picture</button>
<?php
$con=mysqli_connect("localhost","root","","recruitment");
$q=mysqli_query($con,"SELECT * from users where username='".mysql_real_escape_string($_SESSION['username'])."'");
while($row=mysqli_fetch_assoc($q)){
/*echo $row['username'].'<br>';*/
if($row['image']==""){
echo'<img id="profile-image" width="50" height="50" src="picture-upload/defaultimage.png" alt="Default profile picture">';
}
else{
echo'<img id="profile-image" width="50" height="50" src="picture-upload/'.$row['image'].'" alt="Profile picture">';
}
}
?>
</div>
</br></span>
<?php echo 'Welcome '.$_SESSION['username'];
echo "<br><a href='logout.php' data-ajax='false'>Logout</a>"; ?> ...</h5>
<?php
//login.php
include_once 'Dbconnect.php';
$JobUser=$_SESSION['username'];
// Select the database.
mysql_select_db($db_database)
or die("Unable to select database: " . mysql_error());
$sql="select * from favorites where username='$JobUser'";
$record=mysql_query($sql);
?>
<div id="output"></div>
<ul data-role="listview" data-inset="true" data-filter="true" id="list_jobs">
<li data-role="list-divider">
<?php
while($users=mysql_fetch_assoc($record)){
echo"<tr>";
echo"<td>".$users['jobid']."</td>";
echo"<td>".$users['jobcity']."</td>";
echo"<td>".$users['jobtitle']."</td>";
echo"</tr>";
}
exit;
?>
</li>
</ul>
</div>
<div data-role="footer">
<h4>©2016 • Genesis M&C Holdings Pty</h4>
</div>
</div>

How to retrieve specific value from Database(mysql) with php

Here I am displaying 4 images on my page from database.
Table equipments with columns:
equi_id, equi_name, equi_type, equi_descp, equi_img
Markup:
<!--Content-->
<center><b><u><font size="6em">Our Equipments</font></center></b></u>
<div class="container" id="content-img">
<div class = "row" id="img-div" data-toggle="modal" data-target="#content-modal">
<?php
include("database.php");
$q="select * from equipments WHERE eq_type = 'chest'";
$result=mysql_query($q,$con);
while($res=mysql_fetch_array($result))
{
echo "<div class='col-md-6' id='".$res['equi_name']."'<span id='equip_head'><b><center>".$res['equi_name']."</center></b></span> <br /> <img src='".$res['equi_img']."' class='img-responsive'></div>";
}
?>
</div>
</div>
I want to retrieve the description (equi_descp) from the same table when clicking on any image. This code is bootstrap enabled.
<!--Content Pop-Up-->
<!-- Modal -->
<div id="content-modal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<?php
include("database.php");
$q="select * from equipments WHERE eq_type = 'chest'";
$result=mysql_query($q,$con);
while($res=mysql_fetch_array($result))
{
echo "<h4 class='modal-title'>".$res['equi_name']."</h4>";
}
echo "</div>";
?>
<?php
include("database.php");
$q="select * from equipments WHERE eq_type = 'chest'";
$result=mysql_query($q,$con);
echo "<div class='modal-body'>";
while($res=mysql_fetch_array($result))
{
echo "<p>'".$res['equi_descp']."'</p>";
}
?>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
With my code, click on any image returns the description of all the images not just the one that is clicked on.
How can I fix my code to only display the description of the image that is clicked on?
Sorry for my bad English.
Thanks in advance
Modify the WHERE part of the query in your popup to target the specific item you wish to access. For example, as WHERE equi_id = 5. You obviously need to add the ID to the URL of the popup window. (How exactly, it depends on how you create your popups; your code doesn't demonstrate that.)
Don't forget to properly sanitize the ID variable from the URL before you stick it into your query. Also, you may want to switch to using mysqli_ in place of the deprecated mysql_ database driver.

php form submit isnt inserting into the database

Right, this should be very basic php, however i cannot for the life of me figure out why this is not working.
I have a form which when submit it should grab the fields then insert the data into the database. I have on my index.php a section which actually pulls back info from database and works fine so i cant see this being a connection problem.
db_connection.php i have hashed out the info here as its for my database, but everything is correct
<?php
define("DB_SERVER","**********");
define("DB_USER","*************");
define("DB_PASS","*********");
define("DB_NAME","reviews");
$connection = mysqli_connect(DB_SERVER,DB_USER,DB_PASS,DB_NAME);
if(mysqli_connect_errno()){
die("database connection failed");
}
?>
functions.php
<?php
function redirect_to($new_location) {
header("Location: " . $new_location);
exit;
}
function confirm_query($result){
if(!$result){
die("database query failed");
}
}
function find_reviews($connection){
$query = "SELECT * ";
$query .= "FROM reviews";
$result = mysqli_query($connection,$query);
confirm_query($result);
while($reviews = mysqli_fetch_assoc($result)){
$output = "<li class=\"first\">";
$output .= $reviews["name"];
$output .= "</li>";
$output .= "<li class=\"second\">";
$output .= $reviews["company"];
$output .= "</li>";
$output .= "<li class=\"third\">";
$output .= $reviews["comment"];
$output .= "</li>";
$output .= "<li class=\"line\"></li>";
echo $output;
}
mysqli_free_result($result);
return $reviews;
}
?>
index.php
to note with this, the function find_reviews() works and does grab the information from database. Also the above "db_connection.php" and "functions.php" are required in index.php
<?php
require("includes/header.php");
$page_title = "All County Road Markings";
$description = "Specialising in Road Marking & Car Park Lining. We are a professional established road marking service with over 20 years experience";?>
<?php require("includes/db_connection.php"); ?>
<?php require("includes/functions.php"); ?>
<?php if(isset($_POST["submit"])){
$name = $_POST["name"];
$company = $_POST["company"];
$comment = $_POST["comment"];
$query = "INSERT INTO `reviews` (name,company,comment) VALUES ('$name','$company','$comment')";
$result=mysqli_query($connection,$query);
confirm_query($result);
redirect_to("index.php");
}
?>
<div id="banner"></div>
<div id="paragraph">
<h2>All County Road Markings are a professional established road marking<br>service with over 20 years experience within the industry</h2>
<hr style="width: 1050px;">
</div>
<div id="content">
<div id="left">
<div class="slot">
<div class="top carpark"> </div>
<div class="linkbar">
<h1>Car Parks</h1>
</div><div class="linktext">
<ul class="comments display">
<li>- Car Parking Bays</li>
<li>- Disabled Parking Bays</li>
<li>- Parent and Child Bays</li>
<li>- Lettering</li>
<li>- Hatchings</li>
<li>- Arrows</li>
<li>- Customised Lettering</li>
</ul>
</div>
</div>
<div class="slot">
<div class="top roadmark"> </div>
<div class="linkbar">
<h1>Road Markings</h1>
</div>
<div class="linktext">
<ul class="comments display">
<li>- Hatchings</li>
<li>- Centre Lines</li>
<li>- Double Yellow lines</li>
<li>- Give way junctions</li>
<li>- Reinstatement of existing markings</li>
</ul>
</div>
</div>
<div class="slot">
<div class="top sportcourt">
</div>
<div class="linkbar">
<h1>Sports/Playground Court</h1>
</div>
<div class="linktext">
<ul class="comments display">
<li>- Tennis Court</li>
<li>- Basketball Court</li>
<li>- 5 A side Court</li>
<li>- Netball Court </li>
<li>- Reinstatement of existing markings</li>
<li>- Custom designs available</li>
</ul>
</div>
</div>
</div>
<div id="right">
<div id="rightbar">
<h2 style="color: white;">Testimonials</h2>
</div>
<div id="comment">
<ul class="comments">
<?php echo find_reviews($connection); ?>
</ul>
</div>
<div id="write">
<p style="margin: 0px; padding-top: 5px;color: grey; font-size: 1.25em;">Click to write a review...<p>
</div>
</div>
<div id="quote"><div class="link-text">contact us</div></div>
</div>
<div id="add">
<div id="close"></div>
<form action="index.php" method="POST">
<div id="name"> Name:<br/><span>Please Enter Full Name</span>
<input type="text" name="name" id="textbox">
</div>
<div id="company"> Company<br/><span>Please Enter Company Name</span>
<input type="text" name="company" id="textbox1">
</div>
<div id="review"> Review<br/><span>Please Enter Review</span>
<textarea name="comment" id="reviewComment"></textarea>
</div>
<div id="save">
<input type="submit" name="submit">
</div>
</form>
</div>
</body>
</html>
ok so can anyone see anything that i am doing wrong? as when the form is submitted it is just not inserting into the database.
EDIT::
when i try echo mysqli->error; i get following error:
Parse error: syntax error, unexpected T_OBJECT_OPERATOR, expecting ',' or ';' in /hermes/bosoraweb140/b484/ipg.allcountyroadmarking/index.php on line 17
So i changed it to
if(!results){
echo "hello";
}
and i do not see the "hello" so it is indicating that i am not even getting into the part that it deals with the post fields
SELF RESOLVED:::::
Ive fixed it, i changed action="index.php" to action=""
i dont understand, it should have worked , but for some reason having the action blank worked. both should be acceptable !
The if statement for $_POST['submint'] might be false on every submit. Maybe try !empty($_POST)
The form action which was set to
<form action="index.php" method="POST">
did not work, however i do not see why not as it is referencing the current page.
However changing it to this resolved the problem.
<form action="" method="POST">
Well you got the php in the same file so that maybe why the action="" is working if it defaults to the same page.. action="index.php" should prepend the current web address. Maybe try putting the full web address in the action="the url for index.php" to see if that works. If does then action="index.php" must not be going to the right file.

Categories