Session Variables in Datatables Plugin - php

I am creating a PHP/MySQL based application and it need to be able to carry over session variables into the DataTable plugin I use on a page in my app. The application is rather complicated, so I will explain how it works before I ask specific questions.
On index.php, there is a dropdown menu that shows the departments that use this application within my organization. The department list is generated by a mySQL table that has their department name and department code. The $dept variable stores the department code value from the selected option in the dropdown menu on submit. In turn, the $_SESSION["department"] variable stores $dept and redirects to the checkin page if successful.
<?php
require_once('connection.php');
session_start();
if (isset($_POST['submit']))
{
$dept = $_POST['dept'];
$_SESSION["department"] = $dept;
header("Location: checkin.php");
}
?>
<!doctype html>
<html class="no-js" lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Visitor Management</title>
<link rel="stylesheet" href="css/foundation.min.css" />
<link rel="stylesheet" href="css/app.css" />
<link type="text/css" rel="stylesheet" href="http://fast.fonts.net/cssapi/24365087-b739-4314-af6e-741946b60bef.css"/>
<link type="text/css" rel="stylesheet" href="http://fast.fonts.net/cssapi/b05259d9-ca62-44a8-8a19-d3facdbd64df.css"/>
<link type="text/css" rel="stylesheet" href="http://fast.fonts.net/cssapi/2603d516-f938-4b52-ae3a-11d25bb4c555.css"/>
<link type="text/css" rel="stylesheet" href="http://fast.fonts.net/cssapi/510266cf-74ab-4fa8-9b39-dd37b90d6ab0.css"/>
</head>
<body>
<!-- nav -->
<div class="top-bar">
<div class="top-bar-left">
<ul class="menu">
</ul>
</div>
<div class="top-bar-right">
</div>
</div>
<div class="row text-center" style="margin-top: 5%;">
<h1>Syracuse University</h1>
<h2>Visitor Management</h2>
<br/>
<form id="dept" method="post" name="dept">
<?php
echo "<select name='dept'>";
echo '<option>'.'Please select a department'.'</option>';
$query = mysqli_query($VisitorManagement, "SELECT * FROM departments");
while($row=mysqli_fetch_array($query))
{
echo "<option value='". $row['code']."'>".$row['name']
.'</option>';
}
echo '</select>';
?>
<input type="submit" class="button" value="Submit" name="submit">
</form>
</div>
<script src="js/vendor/jquery.min.js"></script>
<script src="js/vendor/what-input.min.js"></script>
<script src="js/foundation.min.js"></script>
<script src="js/app.js"></script>
</body>
</html>
The session variable is then carried throughout the site and is used to determine which table needs to be shown. For instance, in checkin.php, we need to display staff members in a dropdown list. We have multiple tables based on the departments using the application. One table we have is called ts_staff If the session variable is stored as the string ts, we do the following steps to make sure the app is connecting to the right database:
We store the session variable from index.php into a global variable on checkin.php $dept = $_SESSION[department];
We create another new variable to concatenate the global variable and the _staff string which is used in all our mySQL staff tables: $staffTable = $dept . "_staff";
Lastly, we use the $staffTable variable as the database table that needs to be displayed: $query = mysqli_query($VisitorManagement, "SELECT * FROM {$staffTable}");
Here's the full checkin.php code:
<?php
// connect to database
require_once('connection.php');
session_start();
//get session variable, if empty, unset and logout
if(empty($_SESSION['department'])) {
session_unset();
session_destroy();
header("Location: index.php");
} else {
$dept = $_SESSION[department];
}
//submit values on submit
if (isset($_POST['submit']))
{
// store form data values
$suid = mysqli_real_escape_string($VisitorManagement, $_POST['suid']);
$staff = mysqli_real_escape_string($VisitorManagement, $_POST['staff']);
$checkinTable = $dept . "_checkin";
// insert varaibles into table rows
$sql = "INSERT INTO {$checkinTable} (suid, staffMember) VALUES ('$suid', '$staff')";
// check if row was inserted correctly
if (mysqli_query($VisitorManagement, $sql)) {
header('Location: thank-you.php');
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($VisitorManagement);
}
}
?>
<!doctype html>
<html class="no-js" lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Visitor Management</title>
<link rel="stylesheet" href="css/foundation.min.css" />
<link rel="stylesheet" href="css/app.css" />
<link type="text/css" rel="stylesheet" href="http://fast.fonts.net/cssapi/24365087-b739-4314-af6e-741946b60bef.css"/>
<link type="text/css" rel="stylesheet" href="http://fast.fonts.net/cssapi/b05259d9-ca62-44a8-8a19-d3facdbd64df.css"/>
<link type="text/css" rel="stylesheet" href="http://fast.fonts.net/cssapi/2603d516-f938-4b52-ae3a-11d25bb4c555.css"/>
<link type="text/css" rel="stylesheet" href="http://fast.fonts.net/cssapi/510266cf-74ab-4fa8-9b39-dd37b90d6ab0.css"/>
</head>
<body>
<!-- nav -->
<div class="top-bar">
<div class="top-bar-left">
<ul class="menu">
<li>Check-In</li>
</ul>
</div>
<div class="top-bar-right">
<ul class="menu">
<li>Admin Login</li>
<li>Logout</li>
</ul>
</div>
</div>
<div class="row text-center" style="margin-top: 5%;">
<h1>Syracuse University</h1>
<!-- replace with whatever department they select -->
<h2>Technical Services</h2>
</div>
<div class="row">
<form id="checkin" method="post" name="checkin">
<div class="row">
<div class="medium-12 columns">
<label>Please Swipe Your SUID Card
<input type="text" placeholder="SUID Number Here" id="suid" name="suid" required>
</label>
</div>
<div class="medium-12 columns">
<label>Who Are You Here to See?
<?php
$staffTable = $dept . "_staff";
echo "<select name='staff'>";
echo '<option value="">'.'Please select a staff member'.'</option>';
$query = mysqli_query($VisitorManagement, "SELECT * FROM {$staffTable}");
while($row=mysqli_fetch_array($query))
{
echo "<option value='". $row['fullName']."'>".$row['fullName']
.'</option>';
}
echo '</select>';
// close connection
mysqli_close($VisitorManagement);
?>
</label>
</div>
<div class="medium-12 columns">
<input type="submit" class="button" value="Submit" name="submit">
</div>
</div>
</form>
</div>
<script src="js/vendor/jquery.min.js"></script>
<script src="js/vendor/what-input.min.js"></script>
<script src="js/foundation.min.js"></script>
<script src="js/app.js"></script>
</body>
</html>
The problem is that on reports.php, I am using the DataTables plugin to dynamically organize and filter a table, but I need to be able to carry the session variable over into the plugin so it knows to organize the specific table based on what the user selected on the index.php screen.
reports.php just calls DataTables and using another page, response.php to turn the data from the table into JSON to be displayed. Here's reports.php:
<?php session_start();
if(empty($_SESSION['department'])) {
session_unset();
session_destroy();
header("Location: index.php");
} else {
$dept = $_SESSION[department];
}
$checkinTable = $dept . "_checkin";
?>
<!doctype html>
<html class="no-js" lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Visitor Management</title>
<link rel="stylesheet" href="../css/foundation.min.css" />
<link rel="stylesheet" href="../css/app.css" />
<link type="text/css" rel="stylesheet" href="http://fast.fonts.net/cssapi/24365087-b739-4314-af6e-741946b60bef.css"/>
<link type="text/css" rel="stylesheet" href="http://fast.fonts.net/cssapi/b05259d9-ca62-44a8-8a19-d3facdbd64df.css"/>
<link type="text/css" rel="stylesheet" href="http://fast.fonts.net/cssapi/2603d516-f938-4b52-ae3a-11d25bb4c555.css"/>
<link type="text/css" rel="stylesheet" href="http://fast.fonts.net/cssapi/510266cf-74ab-4fa8-9b39-dd37b90d6ab0.css"/>
<link type="text/css" rel="stylesheet" href="https://cdn.datatables.net/r/dt/jq-2.1.4,jszip-2.5.0,pdfmake-0.1.18,dt-1.10.9,af-2.0.0,b-1.0.3,b-colvis-1.0.3,b-html5-1.0.3,b-print-1.0.3,se-1.0.1/datatables.min.css"/>
</head>
<body>
<?php
if (!isset($_SESSION['user'])) {
header("Location: ../login.php"); // If session is not set that redirect to Login Page
}
?>
<div class="top-bar admin">
<div class="top-bar-left">
<ul class="menu">
<li class="menu-text">Visitor Management</li>
</ul>
</div>
<div class="top-bar-right">
<ul class="menu">
<li>Logout</li>
<li>Help</li>
</ul>
</div>
</div>
<div class="medium-2 columns dash">
<ul>
<li>Dashboard</li>
<li>Staff</li>
<li class="active">Reports</li>
</ul>
</div>
<div class="medium-10 columns">
<div class="row checkin">
<h2>Reports</h2>
<table class="checkin" id="checkin">
<thead>
<tr>
<th>ID</th>
<th>SUID #</th>
<th>Staff Member</th>
<th>Student Name</th>
<th>Student Email</th>
<th>Check In Date/Time</th>
</tr>
</thead>
</table>
<!--<div class="float-left">
Export to Excel
</div>
<div class="float-right">
</div>-->
</div>
</div>
<script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.2.min.js"></script>
<script src="../js/vendor/what-input.min.js"></script>
<script src="../js/foundation.min.js"></script>
<script src="../js/app.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/r/dt/jq-2.1.4,jszip-2.5.0,pdfmake-0.1.18,dt-1.10.9,af-2.0.0,b-1.0.3,b-colvis-1.0.3,b-html5-1.0.3,b-print-1.0.3,se-1.0.1/datatables.min.js"></script>
<script>
$(document).ready(function() {
$('#checkin').DataTable({
"bProcessing": true,
"serverSide": false,
"dom": 'lBfrtip',
"buttons": [
{
extend: 'collection',
text: 'Export',
buttons: [
'copy',
'excel',
'csv',
'pdf',
'print'
]
}
],
"ajax":{
url :"response.php", // json datasource
type: "post", // type of method ,GET/POST/DELETE
data: {}
}
});
});
</script>
</body>
</html>
Here's response.php:
<?php
//include connection file
include_once("../connection.php");
// initilize all variable
$params = $columns = $totalRecords = $data = array();
$params = $_REQUEST;
//define index of column
$columns = array(
0 => 'id',
1 => 'suid',
2 => 'staffMember',
3 => 'studentName',
4 => 'studentEmail',
5 => 'checkinDateTime'
);
$where = $sqlTot = $sqlRec = "";
// check search value exist
if( !empty($params['search']['value']) ) {
$where .=" WHERE ";
$where .=" ( studentName LIKE '".$params['search']['value']."%' ";
$where .=" OR staffMember LIKE '".$params['search']['value']."%' ";
$where .=" OR studentEmail LIKE '".$params['search']['value']."%' ";
$where .=" OR suid LIKE '".$params['search']['value']."%' ";
$where .=" OR checkinDate LIKE '".$params['search']['value']."%' )";
}
// getting total number records without any search
$sql = "SELECT id, suid, staffMember, studentName, studentEmail, date_format(checkinDateTime, '%b %d, %Y, %h:%i %p') as checkinDateTime FROM `ts_checkin`";
$sqlTot .= $sql;
$sqlRec .= $sql;
//concatenate search sql if value exist
if(isset($where) && $where != '') {
$sqlTot .= $where;
$sqlRec .= $where;
}
//$sqlRec .= " ORDER BY ". $columns[$params['order'][0]['column']]." ".$params['order'][0]['dir']." LIMIT ".$params['start']." ,".$params['length']." ";
$queryTot = mysqli_query($VisitorManagement, $sqlTot) or die("database error:". mysqli_error($VisitorManagement));
$totalRecords = mysqli_num_rows($queryTot);
$queryRecords = mysqli_query($VisitorManagement, $sqlRec) or die("error to fetch check-in data");
//iterate on results row and create new index array of data
while( $row = mysqli_fetch_row($queryRecords) ) {
$data[] = $row;
}
$json_data = array(
"draw" => intval( $params['draw'] ),
"recordsTotal" => intval( $totalRecords ),
"recordsFiltered" => intval($totalRecords),
"data" => $data // total data array
);
echo json_encode($json_data); // send data as json format
?>
In response.php, I need to able to replace ts_checkin, which is shown on this line:
$sql = "SELECT id, suid, staffMember, studentName, studentEmail, date_format(checkinDateTime, '%b %d, %Y, %h:%i %p') as checkinDateTime FROM `ts_checkin`";`
with a variable called $checkinTable that would concatenate similar to how checkin.php does with the staff table. So essentially I would like to have $checkinTable = $dept . "_checkin" with $dept equaling the value of the session variable.
When I go to do this, I get this error from DataTables: DataTables warning: table id=checkin - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1
Is it possible to get this working? I would like to keep DataTables as its the best way to achieve on-the-fly table filtering, searching, and sorting (plus it's a highly requested feature by our departments). But I need to be able to set the table based on the session variable.
I apologize for the length of this question. If there needs to be clarification, let me know.

I'm not certain to understand the question...
Are you saying this is not working ?
Did you try it written like this?
(notice the space after FROM. It is necessary!)
$checkinTable = $dept . "_checkin";
$sql = "SELECT id, suid, staffMember, studentName, studentEmail, date_format(checkinDateTime, '%b %d, %Y, %h:%i %p') as checkinDateTime FROM " . $checkinTable;
For sure, $dept has also to be defined.
And the resulting $checkinTable has to be an existing table name.
Ok...
This looks to be missing in your response.php:
session_start();
$dept = $_SESSION[department];
$checkinTable = $dept . "_checkin";

Related

Retrieving and displaying logged in info in PHP

I'm trying to retrieve my logged in user data to no avail. Please check my
enter code here private function getUserData($user_name)
{
// if database connection opened
if ($this->databaseConnection()) {
// database query, getting all the info of the selected user
$query_user = $this->db_connection->prepare("SELECT * FROM users WHERE user_name='$_SESSION['user_name']'");
$query_user->bindValue(':user_name', $user_name, PDO::PARAM_STR);
$query_user->execute();
// get result row (as an object)
return $query_user->fetchObject();
} else {
return false;
}
}
Got the way to move about it ,Thanks #ADyson for the response and follow up
code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>YOUR ORDER , We will contact you in a few !!!!</title>
<link href="assets/css/bootstrap.min.css" rel="stylesheet">
<link href="assets/css/main.css" rel="stylesheet">
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<?php include 'header.php'; ?>
<section>
<div class="container">
<strong class="title">MY ORDERS</strong>
</div>
<div class="profile-box box-left">
<?php
require('db.php');
// SQL query
$strSQL = "SELECT user_name, phone, firstname, lastname, service, referal,user_registration_datetime FROM users WHERE user_name = '".$_SESSION['user_name']."'";
// Execute the query (the recordset $rs contains the result)
$rs = mysqli_query($myConnection, $strSQL);
// Loop the recordset $rs
// Each row will be made into an array ($row) using mysqli_fetch_array
while($row = mysqli_fetch_array($rs)) {
echo WORDING_PROFILE_PICTURE . '<br/>' . $login->user_gravatar_image_tag;
echo "<div class='info'> <strong>NAME:</strong> <span>".$row['firstname'].", ".$row['lastname']."</span></div>";
echo "<div class='info'><strong>phone No:</strong> <span>".$row['phone']."</span></div>";
echo "<div class='info'><strong>SERVICE:</strong> <span>".$row['service']."</span></div>";
echo "<div class='info'><strong>REFERAL:</strong> <span>".$row['referal']."</span></div>";
echo "<div class='info'><strong>DATE QUERIED:</strong> <span>".$row['user_registration_datetime']."</span></div>";
}
// Close the database connection
mysqli_close($myConnection);
?>
<div class="options">
<a class="btn btn-primary" href="editprofile.php">Edit Profile</a>
<a class="btn btn-success" href="changepassword.php">Change Password</a>
</div>
</div>
</section>
<script src="assets/js/jquery-3.1.1.min.js"></script>
<script src="assets/js/bootstrap.min.js"></script>
<script src="assets/js/main.js"></script>
</body>
</html>

Issue with foreach loop updating every record, rather than the ones just selected in a checkbox

I have a page with a dropdown box at the top populated from the database, when I select an item from the dropdown it gives a list of results with a checkbox at the end of each line, I want to be able to select, using each checkbox, any number of results, and submit a value back into a field in the database for each result selected.
I sort of have this working, but it submits the value to every field in the database, rather than just the ones selected
<?php
require_once("models/config.php");
if (!securePage($_SERVER['PHP_SELF'])){die();}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="shortcut icon" href="favicon.ico">
<title>Stock Items</title>
<!-- Bootstrap CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- bootstrap theme -->
<link href="css/bootstrap-theme.css" rel="stylesheet">
<!--external css-->
<!-- font icon -->
<link href="css/elegant-icons-style.css" rel="stylesheet" />
<link href="css/font-awesome.min.css" rel="stylesheet" />
<!-- full calendar css-->
<link href="assets/fullcalendar/fullcalendar/bootstrap-fullcalendar.css" rel="stylesheet" />
<link href="assets/fullcalendar/fullcalendar/fullcalendar.css" rel="stylesheet" />
<!-- easy pie chart-->
<link href="assets/jquery-easy-pie-chart/jquery.easy-pie-chart.css" rel="stylesheet" type="text/css" media="screen"/>
<!-- owl carousel -->
<link rel="stylesheet" href="css/owl.carousel.css" type="text/css">
<link href="css/jquery-jvectormap-1.2.2.css" rel="stylesheet">
<!-- Custom styles -->
<link rel="stylesheet" href="css/fullcalendar.css">
<link href="css/widgets.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<link href="css/style-responsive.css" rel="stylesheet" />
<link href="css/xcharts.min.css" rel=" stylesheet">
<link href="css/jquery-ui-1.10.4.min.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js IE8 support of HTML5 -->
<!--[if lt IE 9]>
<script src="js/html5shiv.js"></script>
<script src="js/respond.min.js"></script>
<script src="js/lte-ie7.js"></script>
<![endif]-->
</head>
<body>
<!-- container section start -->
<section id="container" class="">
<?php include("navigation.php"); ?>
<!--main content start-->
<section id="main-content">
<section class="wrapper">
<!--overview start-->
<div class="row">
<div class="col-lg-12">
<h3 class="page-header"><i class="fa fa-lightbulb-o"> </i>Stock</h3>
<ol class="breadcrumb">
<li><i class="fa fa-home"></i>Home</li>
<li><i class="fa fa-lightbulb-o"></i>Stock</li>
</ol>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<section class="panel">
<header class="panel-heading">
All Stock
</header>
<div class="panel-body">
<form class="form-horizontal" method="post" action="">
<div class="form-group">
<div class="col-lg-8">
<select name="search" class="form-control" required >
<?php
// connect to the database
require_once('models/db-settings.php');
$conn = mysql_connect($db_host, $db_user, $db_pass, $db_name) or die("Error " .mysql_error($conn));
mysql_select_db($db_name);
$query = "SELECT `id`, `description` FROM `stock_templates`";
$stock_templates = mysql_query($query);
echo "<option value=''>Select Stock Template</option>";
while ($description=mysql_fetch_assoc($stock_templates)) {
echo "<option value='" . $description['id'] . "'>" . $description['description'] . "</option>";
}
?>
</select>
</div>
<div class="col-lg-1">
<input type="submit" name="filter" value="Search" class="btn btn-success" />
</div>
</div>
</form><br><br>
<?php
if(isset($_POST['formSubmit']))
{
$aDoor = $_POST['check_list'];
if(empty($aDoor))
{
echo("<p>You didn't select any items to add to lease.</p>\n");
}
else
{
$N = count($aDoor);
echo("<p>You selected $N item(s) to add to lease: ");
for($i=0; $i < $N; $i++)
{
echo($aDoor[$i] . " ");
}
echo("</p>");
}
}
function IsChecked($chkname,$value)
{
if(!empty($_POST[$chkname]))
{
foreach($_POST[$chkname] as $chkval)
{
if($chkval == $value)
{
return true;
}
}
}
return false;
}
?>
<?php
ob_start( );
if(!empty($_POST['check_list'])) {
foreach($_POST['check_list'] as $check) {
$query = mysql_query("UPDATE stock SET lease_id = $lease_id");
$result2 = mysql_query($query);
// check if sent
if ($result2) {
?>
<div class="alert alert-success fade in">
<button data-dismiss="alert" class="close close-sm" type="button">
<i class="icon-remove"></i>
</button>
<strong>Well done!</strong> Your lease items have been successfully saved.
</div>
<?php
} else {
?>
<div class="alert alert-block alert-danger fade in">
<button data-dismiss="alert" class="close close-sm" type="button">
<i class="icon-remove"></i>
</button>
<strong>Oh snap!</strong> We could not save your lease items.
</div>
<?php
}
}
}
?>
<?php
// connect to the database
require_once('models/db-settings.php');
$conn = mysql_connect($db_host, $db_user, $db_pass, $db_name) or die("Error " .mysql_error($conn));
mysql_select_db($db_name);
// Extract filter information
$count = 0;
$search = mysql_escape_string(#$_POST['search']);
// select data from the database
$query2 = "SELECT * FROM `stock_templates` ORDER BY `stock_templates`.`id` DESC LIMIT 0";
// Perform Logic
if (array_key_exists("filter", $_POST)) {
// query based on search term
$query2 = "SELECT * FROM `stock` WHERE $search=stocktemplate_id AND lease_id=0";
}
$result2 = mysql_query($query2);
// Result
if (mysql_num_rows($result2) < 1) {
echo "<div align='center'><h2>Please select a stock template above and click search</h2></div>";
}
?>
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post" class="form-horizontal" name="check_list[]">
<div class="form-group">
<label class="control-label col-lg-1" for="lease_id">Lease Number *</label>
<div class="col-lg-10">
<select name="lease_id" class="form-control">
<?php
// connect to the database
require_once('models/db-settings.php');
$conn = mysql_connect($db_host, $db_user, $db_pass, $db_name) or die("Error " .mysql_error($conn));
mysql_select_db($db_name);
$query = "SELECT `id`, `leasenumber` FROM `lease`";
$leases = mysql_query($query);
echo "<option value=''>Select Lease..........</option>";
while ($lease=mysql_fetch_assoc($leases)) {
echo "<option value='" . $lease['id'] . "'>" . $lease['leasenumber'] . "</option>";
}
?>
</select>
</div>
</div>
<table class="table table-hover">
<thead>
<tr>
<th>Item ID</th>
<th>Description</th>
<th>Barcode</th>
<th>Serial</th>
<th>Add To Lease</th>
</tr>
</thead>
<?php
while ($row = mysql_fetch_array($result2))
{
$id = $row["id"];
$lease_id = $row["lease_id"];
$barcode = $row["barcode"];
$serial = $row["serial"];
$stocktemplate_id = $row["stocktemplate_id"];
$qa = 0;
?>
<tbody>
<tr>
<td><?php print $id ?></td>
<td><?php $q = mysql_query("SELECT description FROM stock_templates WHERE id = '$stocktemplate_id'"); while ($row = mysql_fetch_array($q)){$qa = $row["description"];} print $qa ?></td>
<td><?php print $barcode ?></td>
<td><?php print $serial ?></td>
<td><input type="checkbox" name="check_list[]" value="<?php print $id ?>" /></td>
<td></td>
</td>
</tr>
</tbody>
<?php
}
?>
</table>
<input class="btn btn-danger" type="submit" name="formSubmit" value="Add Selected To Lease" />
</div>
</form>
</section>
</div>
</div>
</section>
</section>
<!--main content end-->
</section>
<!-- container section end -->
<!-- javascripts -->
<script src="js/jquery.js"></script>
<script src="js/bootstrap.min.js"></script>
<!-- nice scroll -->
<script src="js/jquery.scrollTo.min.js"></script>
<script src="js/jquery.nicescroll.js" type="text/javascript"></script>
<!-- jquery ui -->
<script src="js/jquery-ui-1.9.2.custom.min.js"></script>
<!--custom checkbox & radio-->
<script type="text/javascript" src="js/ga.js"></script>
<!--custom switch-->
<script src="js/bootstrap-switch.js"></script>
<!--custom tagsinput-->
<script src="js/jquery.tagsinput.js"></script>
<!-- colorpicker -->
<!-- bootstrap-wysiwyg -->
<script src="js/jquery.hotkeys.js"></script>
<script src="js/bootstrap-wysiwyg.js"></script>
<script src="js/bootstrap-wysiwyg-custom.js"></script>
<!-- ck editor -->
<script type="text/javascript" src="assets/ckeditor/ckeditor.js"> </script>
<!-- custom form component script for this page-->
<script src="js/form-component.js"></script>
<!-- custome script for all page -->
<script src="js/scripts.js"></script>
</body>
</html>
No worries. Just put the code of insert query inside foreach() loop. Like this:
foreach($_POST['check_list'] as $item)
{
$sql="INSERT/UPDATE Query";
//for example
$sql = "INSERT INTO table_demo (field_1, TARGET_FIELD, field_2, field_3) VALUES (val_1, $item, val_2, val_3)";
$insert = mysqli_query($connection,$sql);
}
//next code of your choice
That is really Easy to give a go.
See this is same as you want.
In this link the first answer by Sean Valsh is your solution.
Giving the array as name of every checkbox will give you only chacked option's id in array while submitted.
https://stackoverflow.com/a/4997271/6834980
Ask if still have the problem. Happy to help.

PHP Basic Random Quote Generator. How do I prevent quotes that have appeared recently?

EDIT: Thank you for correcting the formatting... did not notice that mistake
I have completed this basic quote generator as a first project, but have noticed that it frequently displays the same quote upon refresh. Granted, there are only five at the moment, but this problem might still be apparent as I fill the database. I am currently learning JQuery AJAX for a more advanced one - but am only starting. To my knowledge, this is not a duplicate question. Displays database query upon reload. Thank you!
Here is the code:
connect.php:
<?php
$connection = new mysqli('localhost', 'root', '', 'random_quotes');
if ($connection->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ')'
. $mysqli->connect_error);
}
?>
functions.php:
<?php
require ('connect.php');
$query = "SELECT id, quote, author FROM quotes ORDER BY RAND() LIMIT 1";
$getQuote = $connection->query($query);
?>
HTML:
<!doctype html>
<html lang="en">
<?php
require ('includes/connect.php');
require ('includes/functions.php');
?>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<link href='https://fonts.googleapis.com/css?family=Candal' rel='stylesheet' type='text/css'>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<div class="container-fluid text-center">
<h1>Random Quote Generator</h1>
<p>Some of my favourite all around quotes!</p>
<br/>
<button class="btn btn-default" onclick="newQuote()" type="submit">New Quote
</button>
<div class="quote_wrap text-center">
<span class="quote">
<?php
while($row = $getQuote->fetch_assoc()){
$stringID = $row['id'];
$stringQuote = $row['quote'];
$stringAuthor = $row['author'];
echo $stringQuote;
}
?>
</span>
</br>
<div class="author text-center"><?php echo $stringAuthor?></div>
<div class="quoteid" id="<?php echo $stringID?>"></div>
</div>
</div>
<script src="https: /ajax.googleapis.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
<script type="text/javascript">
function newQuote() {
location.reload();}
</script>
</body>
</html>
Generate a random number and then access quote by that id. May work better..
$query = "SELECT COUNT(*) as noQuotes FROM quotes ";
$result = $connection->query($query);
$row = $result->fetch_assoc();
$noQuotes = $row["noQuotes"];
srand(time());
//echo(rand(1,$noQuotes));
$randNo = rand(1,$noQuotes);
$query = "SELECT id, quote, author FROM quotes WHERE id = $randNo ";
$getQuote = $connection->query($query);

$_SESSION in PHP is always returning 1

I'm trying to develop a login system in PHP which has faculty_login.php which displays faculty_login_option.inc.php which has a login form and if $_SESSION['f_id'] is set it redirects to faculty_upload_option.php. where faculty details are fetched from faculty_table using $f_id = $_SESSION['f_id'] as the primary key.but $_SESSION['f_id'] is always returning 1 and user is logging in as the user whose f_id is 1.
<?php
//faculty login page.faculty_login.php
//if logged in show upload option/show login option.
require_once 'resources/core.inc.php';//session is set here
require_once 'resources/connect.inc.php';//init db connection
if(isset($_SESSION['f_id'])&&!empty($_SESSION['f_id'])){
require_once 'faculty_upload_option.inc.php';
}
else{
require_once 'faculty_login_option.inc.php';
}
?>
<?php
/* faculty_login_db.php
* Check if the faculty can login or the credentials are wrong.
*/
require_once 'resources/core.inc.php';
require_once 'resources/connect.inc.php';
if(isset($_POST['f_username'])&&isset($_POST['f_password'])){
if(!empty($_POST['f_username'])&&!empty($_POST['f_password'])){
$username = stripcslashes($_POST['f_username']);
$password = stripcslashes($_POST['f_password']);
$result = $conn->prepare("SELECT f_id FROM faculty_table WHERE f_username= :hjhjhjh AND f_password= :asas");
$result->bindParam(':hjhjhjh', $username);
$result->bindParam(':asas', $password);
$result->execute();
$rows = $result->fetch(PDO::FETCH_NUM);
if($result->rowCount() == 1) {
$_SESSION['f_id'] = $rows ;
$_SESSION['f_username'] = $username;
header('Location:faculty_login.php');
}
else{
header('Location:faculty_login.php?username='.$username);
}
}
else{
header('Location:faculty_login.php');
}
}
else{
header('Location:faculty_login.php');
}
?>
<?php
/* faculty_login_option.php
* faculty login page. check if user exists/ use faculty_login_db.php
*/
?>
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>Home</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0 , maximum-scale=1">
<link rel="stylesheet" href="resources/loginstyle.css">
</head>
<body>
<?php
//<img alt="full screen background image" src="images/orange.jpg" id="full-screen-background-image" />
?>
<div id="back">Home</div>
<div id="header">
<h3>FACULTY LOGIN</h3><br>
</div>
<hr>
<div id="container">
<center>
<form action="faculty_login_db.php" method="post">
<input type="text" onFocus="if(this.value=='Username'){this.value=''}" name="f_username" class="buttons" value="<?php
if(isset($_GET['username']))
{
echo $_GET['username'];
}else{echo 'Username';}
?>"><br>
<input type="password" onFocus="if(this.value=='Password'){this.value='';}" name="f_password" class="buttons" value="Password"><br>
<input type="submit" value="Login" class="lbutton">
</form>
</center>
<?php
if(isset($_GET['username'])){
?>
<div id="errormsg">Username or password is invalid.</div>
<?php
}
?>
</body>
<?php
/* this is faculty_upload_option.inc.php
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
require_once 'resources/core.inc.php';
require_once 'resources/connect.inc.php';
if(isset($_SESSION['f_id'])&&isset($_SESSION['f_username'])&&!empty($_SESSION['f_id'])){
$f_id=trim(isset($_SESSION['f_id']));
if(!empty($f_id)){
$result = $conn->prepare("SELECT * FROM faculty_table WHERE f_id=:id");
$result->bindparam(':id', $f_id);
$result->execute();
$rows = $result->fetchAll();
foreach($rows as $db_rows){
$f_username = $db_rows['f_username'];
$category = $db_rows['category'];
$branch = $db_rows['branch'];
}
//page which should be displayed if user logs in.?>
<html>
<head><title><?php echo $f_username; ?></title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0 , maximum-scale=1">
<link href='http://fonts.googleapis.com/css?family=Indie+Flower|Yanone+Kaffeesatz' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="resources/upload_style.css">
</head>
<body><div id="parent">
<div id="header">
<img src="images/no-profile-image.png" width="30%" id="noimg">
<span id="addfont"><h1><?php echo $f_username;?></h1></span>
<h2><?php echo $category;?></h2>
<p><?php echo $branch;?></p>
<center><div class="buttons" id="left">Home</div><div class="buttons" id="right">Logout</div></center>
</div>
Are you destroying session correctly on logout? Are you setting session id before hitting the condition somewhere? What is the value before hitting the comparion condition?

PHP echo to another page

What i wrong with this code below. I am trying to get it to echo to another page but it does not seem to pick up the data that is on the database.
<?php
{
// connect to server
mysql_connect("localhost", "u", "") or die(mysql_error());
//select database
mysql_select_db("") or die(mysql_error());
//Create a query that selects all data from the PATIENT table where the username and password match
$query = "SELECT`Appointment_id`, `Doctor_id`, `Patient_id`, `Appointment_time`, `Appointment_date` FROM `Appointment`";
//executes query on the database
$result = mysql_query ($query) or die ("didn't query");
//this selects the results as rows
$num = mysql_num_rows ($result);
//if there is only 1 result returned than the data is ok
if ($num == 1)
{
$row=mysql_fetch_array($result);
$_SESSION['Appointment_id'] = $row['Appointment_id'];
$_SESSION['Doctor_id'] = $row['Doctor_id'];
}
}
?>
Appointment.php
<!DOCTYPE html>
<?php
session_start();
?>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<title>
</title>
<link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/jquery.mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
<link rel="stylesheet" href="my.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.mobile/1.2.0/jquery.mobile-1.2.0.min.js">
</script>
<script src="my.js">
</script>
<!-- User-generated css -->
<style>
</style>
<!-- User-generated js -->
<script>
try {
$(function() {
});
} catch (error) {
console.error("Your javascript has an error: " + error);
}
</script>
</head>
<body>
<!-- Home -->
<div data-role="page" id="page1">
<div data-theme="a" data-role="header">
<a data-role="button" data-theme="d" data-icon="arrow-l" data-iconpos="left" class="ui-btn-left">
Back
</a>
<a data-role="button" href="index.html" data-icon="home" data-iconpos="right" data-theme="d"class="ui-btn-right">
Home
</a>
</div>
<div data-role="content">
<?php
{
// connect to server
mysql_connect("localhost", "", "") or die(mysql_error());
//select database
mysql_select_db("") or die(mysql_error());
$query = "SELECT `Appointment_id`, `Doctor_id`, `Patient_id`, `Appointment_time`, `Appointment_date` FROM `Appointment`";
//executes query on the database
$result = mysql_query ($query) or die ("didn't query");
//this selects the results as rows
$num = mysql_num_rows ($result);
//if there is only 1 result returned than the data is ok
if ($num == 1)
{
$row=mysql_fetch_array($result);
$_SESSION['Appointment_id'] = $row['Appointment_id'];
$_SESSION['Doctor_id'] = $row['Doctor_id'];
}
}
?>
</div>
</div>
</body>
</html>
Echo onto this page
<!DOCTYPE html>
<?php
session_start();
?>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<title>
</title>
<link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/jquery.mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
<link rel="stylesheet" href="my.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.mobile/1.2.0/jquery.mobile-1.2.0.min.js">
</script>
<script src="my.js">
</script>
<!-- User-generated css -->
<style>
</style>
<!-- User-generated js -->
<script>
try {
$(function() {
});
} catch (error) {
console.error("Your javascript has an error: " + error);
}
</script>
</head>
<body>
<!-- Home -->
<div data-role="page" id="page1">
<div data-theme="a" data-role="header">
<a data-role="button" data-theme="d" data-icon="arrow-l" data-iconpos="left" class="ui-btn-left">
Back
</a>
<a data-role="button" data-icon="home" data-iconpos="right" data-theme="d"class="ui-btn-right">
Home
</a>
<h3>
Details
</h3>
</div>
<div data-role="content">
<form name="form1" method="post" action="login.php">
<strong>Your Details</strong>
<br />
<br />
Appointment: <?php echo $_SESSION['Appointment_id'];?>
<br />
<br />
Doctor: <?php echo $_SESSION['Doctor_id'];?>
<br />
<br />
</div>
</div>
</body>
</html>
The second section is where the database is picking up the information (Appointment) and the third shows where i need it to display
<!DOCTYPE html>
<?php
session_start();
?>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<meta http-equiv="refresh" content="2;url=details1.php">
<title>
</title>
<link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/jquery.mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
<link rel="stylesheet" href="my.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.mobile/1.2.0/jquery.mobile-1.2.0.min.js">
</script>
<script src="my.js">
</script>
<!-- User-generated css -->
<style>
</style>
<!-- User-generated js -->
<script>
try {
$(function() {
});
} catch (error) {
console.error("Your javascript has an error: " + error);
}
</script>
</head>
<body>
<!-- Home -->
<div data-role="page" id="page1">
<div data-theme="a" data-role="header">
<a data-role="button" data-theme="d" href="login.html" data-icon="arrow-l" data-iconpos="left" class="ui-btn-left">
Back
</a>
<a data-role="button" href="index.html" data-icon="home" data-iconpos="right" data-theme="d"class="ui-btn-right">
Home
</a>
<h3>
Login Process
</h3>
</div>
<div data-role="content">
login.php
<!DOCTYPE html>
<?php
session_start();
?>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<meta http-equiv="refresh" content="2;url=details1.php">
<title>
</title>
<link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/jquery.mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
<link rel="stylesheet" href="my.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.mobile/1.2.0/jquery.mobile-1.2.0.min.js">
</script>
<script src="my.js">
</script>
<!-- User-generated css -->
<style>
</style>
<!-- User-generated js -->
<script>
try {
$(function() {
});
} catch (error) {
console.error("Your javascript has an error: " + error);
}
</script>
</head>
<body>
<!-- Home -->
<div data-role="page" id="page1">
<div data-theme="a" data-role="header">
<a data-role="button" data-theme="d" href="login.html" data-icon="arrow-l" data-iconpos="left" class="ui-btn-left">
Back
</a>
<a data-role="button" href="index.html" data-icon="home" data-iconpos="right" data-theme="d"class="ui-btn-right">
Home
</a>
<h3>
Login Process
</h3>
</div>
<div data-role="content">
<?php
// takes the variables from action script and assigns them php variables names
$user = $_POST ['username'];
$pass = $_POST ['password'];
// if there is a user name and password
if ($user && $pass)
{
// connect to server
mysql_connect("localhost", "", "") or die(mysql_error());
//select database
mysql_select_db("") or die(mysql_error());
//Create a query that selects all data from the PATIENT table where the username and password match
$query = "SELECT * FROM Patient WHERE Username = '$user' AND Password = '$pass'";
//executes query on the database
$result = mysql_query ($query) or die ("didn't query");
//this selects the results as rows
$num = mysql_num_rows ($result);
//if there is only 1 result returned than the data is ok
if ($num == 1)
{
//sends back a data of "Success"
echo "Successful Login";
$row=mysql_fetch_array($result);
$_SESSION['Title'] = $row['Title'];
$_SESSION['First_name'] = $row['First_name'];
$_SESSION['Last_name'] = $row['Last_name'];
$_SESSION['Address'] = $row['Address'];
$_SESSION['Line_2'] = $row['Line_2'];
$_SESSION['Line_3'] = $row['Line_3'];
$_SESSION['Postcode'] = $row['Postcode'];
$_SESSION['Home'] = $row['Home'];
$_SESSION['Mobile'] = $row['Mobile'];
}
else
{
//sends back a message of "failed"
echo "Unsuccessful Login";
}
}
?>
</div>
</div>
</body>
</html>
please add at the top
session_start();
since you are using $_SESSION .. you need to use session_start() immediately after php opening tag
<?php
session_start();
and not only on this page .. session_start() should be there on every page where you want you use session_start() .. otherwise $_SESSION is not accessible..
Please use session_start() on both of the pages, if you dont start that you will not be able to use that
EDIT
Create a test page to see your sessions are working?
if yes then test that on other page
also try adding a simple echo in your if condition where you are setting the session values. If that echo triggers it means your code is correct and something is wrong with SESSION. And if echo dont trigger, it means your code is not correct and sessions are not being set
if your just trying to get the first row
$query = "SELECT `Appointment_id`, `Doctor_id`, `Patient_id`, `Appointment_time`, `Appointment_date` FROM `Appointment` WHERE rownum = 1 ; ";
Edit:
Ok so here I believe the logical error lies
$query = "SELECT `Appointment_id`, `Doctor_id`, `Patient_id`, `Appointment_time`, `Appointment_date` FROM `Appointment`";
$result = mysql_query ($query) or die ("didn't query");
$num = mysql_num_rows ($result);
if ($num == 1)
{
}
Since your query has no WHERE clause, it is returning all records that there are, and You are setting the SESSION values only when there is 1 record. You should also have an else condition to see what happens in real.
Create a query that selects all data from the PATIENT table where the username and password match
But your query does not do that, it gets data for all the PATIENTs
For example if your username and password came from a POSTed form then you could do
$username=mysql_real_escape_string($_POST["username"]);
$password=mysql_real_escape_string($_POST["password"]);
Then you could use both those values inside a WHERE clause. Since I do not know the structure of your tables apart from just reading your query, I can not write it exactly. But just to give you an idea, a where could be like
$query="SELECT id from YourTable where $username='$username' and password='$password'"
Very important to note since you are a beginner : mysql_* functions should no longer be used. If you are starting, don't start with something that's gone. Read about mysqli_* or PDO
Edit 2:
Ok great, so do this
On successful login where you store Patient's details in SESSION, also store Patient_id like $_SESSION['Patient_id'] = $row['Patient_id']; //or maybe its just id. Check your table
On Appointment.php change your query to
$pid=intval($_SESSION["Patient_id"]);
$query = "SELECT Appointment_id, Doctor_id, Patient_id, Appointment_time, Appointment_date FROM Appointment where Patient_id=$pid";
Add an else condition below your if($num==1) { } block like
PHP
else{
echo "Somehow we didn't get 1 record";
die();
}

Categories