autocomplete input with database record - php

I want to add my PhpMyAdmin record into a autocomplete function when someone types a name or something it will show the value in the database to be selected. The values that has to be in my input field is from table address_state
my code:
<?php
if(isset($_POST['search']))
{
$valueToSearch = $_POST['valueToSearch'];
// search in all table columns
// using concat mysql function
$query = "SELECT person_id, person_firstname, person_lastname,
person_email, person_phonenumber,
address_street,address_housenumber,
address_city,address_state,address_zipcode,cv_path
FROM person
inner join address on address.address_id = person.person_address
inner join cv on cv.cv_id = person.person_cv
WHERE CONCAT(`person_firstname`, `person_lastname`, `address_street`, `address_housenumber`, `address_zipcode`, `address_city`, `address_state`, `person_email`, `person_phonenumber` )
LIKE '%".$valueToSearch."%'";
$search_result = filterTable($query);
}
else {
$query = "SELECT person_id, person_firstname, person_lastname,
person_email, person_phonenumber,
address_street,address_housenumber,
address_city,address_state,address_zipcode,cv_path
FROM person
inner join address on address.address_id = person.person_address
inner join cv on cv.cv_id = person.person_cv ";
$search_result = filterTable($query);
}
// function to connect and execute the query
function filterTable($query)
{
$connect = mysqli_connect("localhost", "root", "usbw", "persons");
$filter_Result = mysqli_query($connect, $query);
return $filter_Result;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Detail</title>
<style>
table,tr,th,td
{
border: 1px solid black;
}
</style>
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<form action="admin2.php" method="post" onchange="showUser(this.value)">
<input type="text" name="valueToSearch" placeholder="Hoi" style="margin-left: 50px;">
<input type="submit" name="search" value="Filter"><br><br>
<div id="txtHint">
<table>
<tr>
<th>Voornaam</th>
<th>Achternaam</th>
<th>Straat</th>
<th>Huisnummer</th>
<th>Postcode</th>
<th>Stad</th>
<th>Provincie</th>
<th>Email</th>
<th>Mobiel</th>
<th>cv</th>
<th>delete</th>
</tr>;
<!-- populate table from mysql database -->
<?php while($row = mysqli_fetch_array($search_result)):?>
<tr>
<td><?php echo $row['person_firstname'];?></td>
<td><?php echo $row['person_lastname'];?></td>
<td><?php echo $row['address_street'];?></td>
<td><?php echo $row['address_housenumber'];?></td>
<td><?php echo $row['address_zipcode'];?></td>
<td><?php echo $row['address_city'];?></td>
<td><?php echo $row['address_state'];?></td>
<td><?php echo $row['person_email'];?></td>
<td><?php echo $row['person_phonenumber'];?></td>
<td><?php echo "<a href='http://localhost:8080/website/" . $row['cv_path'] . "'>cv file</a>";?></td>
<td><?php echo "<a href='delete.php?person_id=" . $row['person_id'] . "'>delete</a>";?></td>
</tr>
<?php endwhile;?>
</table>
</div>
</form>
</body>
</html>

Related

applying search or filter to table with pagination

hello kind sirs can you help me with this code. What i try to do is when i type something in the search box, ex. pending it will show the 5 pending reservation per page(5 rows of pending reservation). but when i try it, it shows all the pending reservation which is more than 10.
here is the image
i try something like this.. but it shows nothing
$query = "SELECT * FROM reservations WHERE CONCAT(firstname, lastname, reservationstatus)LIKE '%".$valueToSearch."%' LIMIT " . $this_page_first_result . ',' . $results_per_page";
Here is the whole code
<?php
error_reporting(E_ALL & ~E_NOTICE);
error_reporting(E_ERROR | E_PARSE);
session_start();
?>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "srdatabase";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$results_per_page = 5;
$select= "SELECT * FROM reservations";
$result = mysqli_query($conn, $select);
$number_of_results = mysqli_num_rows($result);
if(!isset($_GET['page']))
{
$page = 1;
}
else
{
$page = $_GET['page'];
}
$this_page_first_result = ($page-1)*$results_per_page;
$sql = "SELECT * FROM reservations LIMIT " . $this_page_first_result . ',' . $results_per_page;
$result = mysqli_query($conn, $sql);
$number_of_pages = ceil($number_of_results/$results_per_page);
?>
<div id="paging-div">
<?php
for($page=1;$page<=$number_of_pages;$page++)
{
echo '<a id="pagingLink" href="adminControl.php?page=' . $page . '">' . $page . '</a>';
}
?>
<?php
if(isset($_POST['search']))
{
$valueToSearch = $_POST['valueToSearch'];
$query = "SELECT * FROM reservations WHERE CONCAT(firstname, lastname, reservationstatus)LIKE '%".$valueToSearch."%'";
$search_result = filterTable($query);
}
else
{
$query = "SELECT * FROM reservations";
$search_result = filterTable($query);
}
function filterTable($query)
{
$conn = mysqli_connect("localhost", "root", "", "srdatabase");
$filter_Result = mysqli_query($conn, $query);
return $filter_Result;
}
?>
</div>
<!DOCTYPE html>
<html>
<head>
<title>Admin Control</title>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<div class="topnav" id="myTopnav">
Home
Speakers
About
Contact
Reservation
Sign Out
<?php echo $_SESSION['firstname']; ?>
Sign Up
Sign In
Admin control
☰
</div>
<br>
<br>
<br>
<br>
<h4 style="padding-left:10px; text-align:center;">Reservation List</h4>
<hr>
<form action="adminControl.php" method="POST">
<input type="text" name="valueToSearch" placeholder="type a value">
<input type="submit" name="search" value="Filter">
</form>
<br>
<br>
<div style="overflow-x:auto;">
<table class="reservations-table">
<tr>
<th class="thFirstName">First Name</th>
<th class="thLastName">Last Name</th>
<th class="thEmailAddress">Email Address</th>
<th class="thContactNumber">Contact Number</th>
<th class="thSpeaker">Speaker</th>
<th class="thTopic">Topic</th>
<th class="thLocation">Location</th>
<th class="thAudience">Audience</th>
<th class="thCount">Count</th>
<th class="thTime">Time</th>
<th class="thDate">Date</th>
<th class="thAction">Reservation Date</th>
<th class="thAction">Status</th>
<th class="thAction">Action</th>
<th class="thAction">Action</th>
</tr>
<?php while($row = mysqli_fetch_array($search_result)):?>
<tr>
<td><?php echo $row['firstname'];?></td>
<td><?php echo $row['lastname'];?></td>
<td><?php echo $row['emailaddress'];?></td>
<td><?php echo $row['contactnumber'];?></td>
<td><?php echo $row['speaker'];?></td>
<td><?php echo $row['topic'];?></td>
<td><?php echo $row['location'];?></td>
<td><?php echo $row['audience'];?></td>
<td><?php echo $row['count'];?></td>
<td><?php echo $row['time'];?></td>
<td><?php echo $row['date'];?></td>
<td><?php echo $row['reservationdate'];?></td>
<td><?php echo $row['reservationstatus'];?></td>
</tr>
<?php endwhile;?>
</table>
</form>
</div>
<?php
$epr='';
$msg='';
if(isset($_GET['epr']))
$epr=$_GET['epr'];
if($epr=='delete')
{
$id=$_GET['id'];
$delete=mysqli_query($conn, "DELETE FROM reservations WHERE id=$id");
if($delete)
header('location:adminControl.php');
else
$msg='Error :'.mysqli_error();
}
?>
<?php
$epr='';
$msg='';
if(isset($_GET['epr']))
$epr=$_GET['epr'];
if($epr=='approve')
{
$id=$_GET['id'];
$approve=mysqli_query($conn, "UPDATE reservations SET reservationstatus='approved' WHERE id=$id");
header('location:adminControl.php');
}
?>
<script>
function myFunction() {
var x = document.getElementById("myTopnav");
if (x.className === "topnav") {
x.className += " responsive";
} else {
x.className = "topnav";
}
}
</script>
<script>
function ifAdmin()
{
document.getElementById("signIn").style.display = "none";
document.getElementById("signUp").style.display = "none";
document.getElementById("signOut").style.display = "block";
document.getElementById("adminControl").style.display = "block";
}
</script>
<script>
function ifNotAdmin()
{
document.getElementById("signIn").style.display = "none";
document.getElementById("signUp").style.display = "none";
document.getElementById("signOut").style.display = "block";
document.getElementById("adminControl").style.display = "none";
}
</script>
<script>
function ifNotLogin()
{
document.getElementById("user").style.display = "none";
document.getElementById("signOut").style.display = "none";
document.getElementById("adminControl").style.display = "none";
}
</script>
<?php
if (isset($_SESSION['signedIn']) && $_SESSION['signedIn'] == true)
//if login
{
if($_SESSION['type'] == 1)
{
echo "<script type='text/javascript'>ifAdmin();</script>";
}
elseif($_SESSION['type'] == 0)
{
echo "<script type='text/javascript'>ifNotAdmin();</script>";
}
}
//if not login
else
{
echo "<script type='text/javascript'>ifNotLogin();</script>";
}
?>
<div id="footer" class="push">Copyright 2017</div>
</body>
</html>
... when i try it, it shows all the pending reservation which is more than 10.
That's because when you hit 2nd, 3rd, ... pages(after navigating from the 1st page), the $_POST array would be empty i.e. $_POST['search'] won't be set, and that's why else{...} part of the code will get executed every time you navigate to 2nd, 3rd, ... pages. Since you're not sending any sensitive data with the form, use GET instead of POST in the method attribute of the form, like this:
<form action="..." method="get">
and get the user inputted data like this:
if (isset($_GET['search'])) {
$valueToSearch = $_GET['valueToSearch'];
...
Subsequently, you need to attach that search query in each of your pagination links, so that the search query would be available when you hop from page to page.
// your code
<?php
for($page=1;$page<=$number_of_pages;$page++)
{
echo "<a id='pagingLink' href='adminControl.php?page=" . $page . "&valueToSearch=". urlencode($_GET['valueToSearch']) ."&search'>" . $page . "</a>";
}
?>
// your code

How to delete a row of table on click of a button and respective data from database?

I have a table which contains chapters and a button in front of each chapter.
Now I want to delete a row when the delete button is clicked and also I want to fire a delete query to delete the row from database.
I tried 2 3 ways to delete a row from table, but its not getting delete.
<!doctype html>
<html>
<head>
<title>Chapters</title>
</head>
<body>
<style>
td {
text-align: left;
}
</style>
<script>
var par = $(this).parent().parent(); //tr
par.remove();
</script>
<table id="example" style="width:50%">
<tr>
<th><font size="5">Chapters</font></th>
</tr>
<?php
$dbh = new PDO('mysql:host=174.13.54;dbname=handbook', 'airman', 'airman');
$stmt = $dbh->prepare("SELECT * FROM chapters");
$stmt->execute();
$results = $stmt->fetchall(PDO::FETCH_ASSOC);
if(count($results) > 0)
{
foreach($results as $chapter)
{
if($chapter['type'] == 1)
{
$type = "SSgt";
}
elseif($chapter['type'] == 2)
{
$type = "TSgt";
}
elseif($chapter['type'] == 3)
{
$type = "MSgt";
}
?>
<tr>
<td><?php $chapter['id']; echo $chapter['title'];echo " " . "(" .$type.")";?></td>
<td><input type="button" value="Delete"></td>
</tr>
<?Php
}
?>
</table>
</body>
</html>
<?php
}
?>
How can I do this? Can anyone help please?
EDIT :
chapterDelete.php
<!doctype html>
<html>
<head>
<title>Chapters</title>
</head>
<form method="post" action="deleteChapter.php" enctype="multipart/form-data">
<body>
<style>
td {
text-align: left;
}
</style>
<table id="example" style="width:50%">
<tr>
<th><font size="5">Chapters</font></th>
</tr>
<?php
$dbh = new PDO('mysql:host="138.75.54;dbname=handbook', 'airman', 'airman12345');
$stmt = $dbh->prepare("SELECT * FROM chapters");
$stmt->execute();
$results = $stmt->fetchall(PDO::FETCH_ASSOC);
if(count($results) > 0)
{
foreach($results as $chapter)
{
if($chapter['type'] == 1)
{
$type = "SSgt";
}
elseif($chapter['type'] == 2)
{
$type = "TSgt";
}
elseif($chapter['type'] == 3)
{
$type = "MSgt";
}
?>
<tr>
<td><?php echo $chapter['title'];echo " " . "(" .$type.")";?></td>
<td><input type="button" class="removeRowButton" id = "<?php $chapter['id']?>" value="Delete"></td>
</tr>
<?Php
}
?>
</table>
</body>
</form>
</html>
<script
$('.removeRowButton').click(function(){
var rowID= $(this).attr('id');
$.get( "deleteChapter.php?rowID=" + rowID, function( error ) {
if(error == 0){
$('tr#' + rowID).remove();
}
else{
alert('MySQL error!');
}
});
});
</script>
<?php
}
?>
deleteChapter.php
<?php
ini_set('display_errors', 1);
error_reporting(1);
ini_set('error_reporting', E_ALL);
$dbh = new PDO('mysql:host=138.75.54;dbname=handbook', 'airman', 'airman12345');
$stmt = $dbh->prepare("DELETE FROM `chapters` WHERE `rowID`= '" . $_GET["rowID"]);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if(count($result) > 0)
{
echo 'row deleted';
}
else{
echo 'row could not delete';
}
?>
Nothing is happening on click of delete button.
EDIT 2 :
<!doctype html>
<html>
<head>
<title>Chapters</title>
</head>
<form method="post" action="chapterDelete.php" enctype="multipart/form-data">
<body>
<style>
td {
text-align: left;
}
</style>
<table id="example" style="width:50%">
<tr>
<th><font size="5">Chapters</font></th>
</tr>
<?php
ini_set('display_errors', 1);
error_reporting(1);
ini_set('error_reporting', E_ALL);
$dbh = new PDO('mysql:host=1775.54;dbname=handbook', 'airman', 'airman');
$stmt = $dbh->prepare("SELECT * FROM chapters");
$stmt->execute();
$results = $stmt->fetchall(PDO::FETCH_ASSOC);
if(count($results) > 0)
{
foreach($results as $chapter)
{
if($chapter['type'] == 1)
{
$type = "SSgt";
}
elseif($chapter['type'] == 2)
{
$type = "TSgt";
}
elseif($chapter['type'] == 3)
{
$type = "MSgt";
}
?>
<tr>
<td><?php echo $chapter['title'];echo " " . "(" .$type.")";?></td>
<td><input type="button" onClick= "this.form.submit()" value="Delete<?php $chapter['id']?>"</input></td>
</tr>
<?Php
}
?>
</table>
</body>
</form>
</html>
<?php
}
function delete($id)
{
$dbh = new PDO('mysql:host=174.138.75.54;dbname=airman_handbook', 'airman', 'airman12345');
$stmt = $dbh->prepare("DELETE FROM `chapters` WHERE `id`= " . $id);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if(count($result) > 0)
{
echo 'row deleted';
}
else{
echo 'row could not delete';
}
}
?>
Can I do like this without using ajax? But it is not working .
You'll need to make an asynchronous (AJAX) call to a .php script that deletes the row from your MySQL table.
First, your table rows should have an ID set with a unique row number, and this number should also be an attribute of the button that is supposed to remove the row (so that we know which row to remove when we press the remove button):
<table>
<tr id="number">
<td>Data</td>
<td><button class="removeRowButton" id="number" value="Delete this row"></td>
</tr>
</table>
That way, you can interact with each row separately.
Your PHP file (e.g. "removerow.php") should look something like this:
// Connect to MySQL database
$error= 0;
$deleteRow= mysql_query("DELETE FROM `tablename` WHERE `rowID`= '" . $_GET["rowID"] . "';") or $error= 1;
echo($error);
And when you get a SUCCESS back, you'll remove the row from the visible HTML table using jQuery:
$('.removeRowButton').click(function(){
var rowID= $(this).attr('id');
$.get( "removerow.php?rowID=" + rowID, function( error ) {
if(error == 0){
$('tr#' + rowID).remove();
}
else{
alert('MySQL error!');
}
});
});

Display Table Results Based on Dropdown Selection

I have a dropdown that is populated by a column in my database. On selection, I want it to display any table results where the column is equal to the value selected in the dropdown. I can get the table headers to display whenever I select a value, but there is no other data that is displayed.
I am doing an echo $q and it is returning the correct value. So it seems to be getting the selected value and passing it to test1.php correctly, so I am guessing there has to be something wrong somewhere in my test1.php script.
How can I fix this so that the database rows that have a column, Product Report Code that are equal to the selection, are displayed?
HTML/PHP:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","test1.php?q="+str,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<form>
<section id="rep_dropdown">
<select onchange="showUser(this.value)" name="users">
<option value="">Product Report Code</option>
<?php foreach($repcode->fetchAll() as $reportcode) { ?>
<option value="<?php echo $reportcode['Product Report Code'];?>"><?php echo $reportcode['Product Report Code'];?></option>
<?php } ?>
</select>
</section>
</form>
<br>
<div id="txtHint"><b>Person info will be listed here...</b></div>
</body>
</html>
test1.php:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<?php
$q = intval($_GET['q']);
echo $q;
$host="xxxxxxxxx";
$dbName="xxxxxxxxx";
$dbUser="xxxxxxxxxxxxxx";
$dbPass="xxxxxx";
$dbh = new PDO( "sqlsrv:server=".$host."; Database=".$dbName, $dbUser, $dbPass);
$sql="SELECT * FROM vProducts WHERE [Product Report Code] = '".$q."'";
$result = sqlsrv_query($dbh,$sql);
?>
<table id="skuTable" cellspacing="5" class="sortable">
<tr class="ui-widget-header">
<th style="display: none">Product ID</th>
<th class="skuRow">Major Category</th>
<th class="skuRow">Minor Category</th>
<th class="skuRow">Report Code</th>
<th class="skuRow">SKU</th>
<th class="skuRow">SKU Description</th>
<th class="skuRow">SKU Status</th>
<th class="skuRow">Create Date</th>
<th class="skuRow">Group ID</th>
<th class="sorttable_nosort">Edit</th>
</tr>
<?php while($row = sqlsrv_fetch_array($result)) { ?>
<tr class="Row" data-code="<?php echo $row['Product Report Code']?>">
<td style="display: none" class="prod_id" id="product_id-<?php echo intval ($row['Product_ID'])?>"><?php echo $row['Product_ID']?></td>
<td class="major_cat" id="major_cat-<?php echo intval ($row['Major Category'])?>"><?php echo $row['Major Category']?></td>
<td class="minor_cat" id="minor_cat-<?php echo intval ($row['Minor Category'])?>"><?php echo $row['Minor Category']?></td>
<td class="rep_code" id="rep_code-<?php echo intval ($row['Product Report Code'])?>" align="center"><?php echo $row['Product Report Code']?></td>
<td class="sku" id="sku-<?php echo intval ($row['SKU'])?>" align="center"><?php echo $row['SKU']?></td>
<td class="sku_desc" id="sku_desc-<?php echo intval ($row['SKU Description'])?>"><?php echo $row['SKU Description']?></td>
<td class="sku_status" id="sku_status-<?php echo intval ($row['SKU Status'])?>" align="center"><?php echo $row['SKU Status']?></td>
<td class="create_date" id="create_date-<?php echo intval ($row['Date'])?>" align="center"><?php echo $row['Date']?></td>
<td class="group_id" id="group_id-<?php echo intval ($row['Group_ID'])?>" align="center"><?php echo $row['Group_ID']?></td>
<td><input type="button" class="edit" name="edit" value="Edit" onclick="enable_value(this)"></td>
</tr>
<?php } ?>
</table>
</body>
</html>
i'm not sure if sql server accepts table columns names like this Product Report Code
if true , then there are a problem in your connection here ,
$dbh = new PDO( "sqlsrv:server=".$host."; Database=".$dbName, $dbUser, $dbPass);
$sql="SELECT * FROM vProducts WHERE [Product Report Code] = '".$q."'";
$result = sqlsrv_query($dbh,$sql);
you are using PDO extension with sqlsrv Extension , which are totally different .
you have to chose one way to connect to your database .
this is a full PDO example :
$dbh = new PDO( "sqlsrv:server=".$host."; Database=".$dbName, $dbUser, $dbPass);
$sql="SELECT * FROM vProducts WHERE [Product Report Code] = :placeholder";
$stm = $dbh->prepare($sql);
$result = $stm->execute(array("placeholder" => $q);
EDIT
you will also need to update this line :
<?php while($row = sqlsrv_fetch_array($result)) { ?>
to :
<?php while($row = $stm->fetch()) { ?>

PHP Save as PDF not working

Good Day!
I have a dropdown menu which select employee number and shows table data on basis of that particular selection. I have save as pdf code which saves table data in pdf. It is working fine but my table column headers are only shown not the values.
I have dropdown in one file having javascript which is sent to another file where my table is shown.
Below is the code for my all files and what I have tried for this so far.
For Dropdown:
<?php
include("connect-db.php");
?>
<html>
<head>
<title>PHP insertion</title>
<link rel="stylesheet" href="css/insert.css" />
<link rel="stylesheet" href="css/navcss.css" />
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","search_empnumber.php?emp_id="+str,true);
xmlhttp.send();
}
}
/*function showAssessories(acc) {
if (acc == "") {
document.getElementById("txtHint2").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint2").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","getassessories.php?emp_id="+acc,true);
xmlhttp.send();
}
}*/
</script>
</head>
<body>
<div class="maindiv">
<?php include("includes/head.php");?>
<?php include("menu.php");?>
<div class="form_div">
<form>
<div class="forscreen">
<h1>Search Records:</h1>
<p>You may search by Employee Number</p>
<select name="employeenumber" class="input" onchange="showUser(this.value)">
<option value="">Please Select Employee Number:</option>
</div>
<?php
$select_emp="SELECT distinct(emp_number) FROM employees";
$run_emp=mysql_query($select_emp);
while($row=mysql_fetch_array($run_emp)){
$emp_id=$row['emp_id'];
$first_name=$row['first_name'];
$last_name=$row['last_name'];
$emp_number=$row['emp_number'];
$total_printers=$row['total_printers'];
$total_scanners=$row['total_scanners'];
$total_pc=$row['total_pc'];
$total_phones=$row['total_phones'];
$other_equips=$row['other_equips'];
?>
<option value="<?php echo $emp_number;?>"><?php echo $emp_number;?></option>
<?php } ?>
</select>
<html>
</form>
</div>
<br>
<div id="txtHint"></div>
<br>
<div id="txtHint2"></div>
</div>
<?php include 'includes/foot.php';?>
</body>
</html>
The function for dropdown: onchange="showUser(this.value)"
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","search_empnumber.php?emp_id="+str,true);
xmlhttp.send();
}
}
search_empnumber.php File:
<!DOCTYPE html>
<html>
<form action="search_empnumber.php" method="POST">
<input type="submit" value="SAVE AS PDF" class="btnPDF" name="submit" />
</form>
<head>
<style>
table {
width: 100%;
border-collapse: collapse;
}
table, td, th {
border: 1px solid black;
padding: 5px;
}
th {text-align: left;}
.link{ color:#00F; cursor:pointer;}
</style>
</head>
<body>
<?php
//$emp_id =($_REQUEST['emp_id']);
$emp_id =($_REQUEST['emp_id']);
$count=1;
include("connect-db.php");
//$sql = "SELECT * from employees where department='".$department."'";
//$sql = "select * from employees as pg inner join accessories as pd on pg.emp_number= pd.emp_number ";
//$result = mysql_query($sql) or die(mysql_error());
//$result = mysql_query($query) or die(mysql_error());
//$emp_id =($_POST['employeenumber']);
$sql="SELECT * FROM employees WHERE emp_number = '".$emp_id."'";
$result = mysql_query($sql) or die(mysql_error());
$count=1;
echo "<table>
<tr>
<th>S.No</th>
<th>First Name</th>
<th>Last Name</th>
<th>Employee Number</th>
<th>Department</th>
<th>Email</th>
<th>Total Printers</th>
<th>Total Scanners</th>
<th>Total Pc</th>
<th>Total Phones</th>
<th>Other Equipments</th>
</tr>";
while($row = mysql_fetch_array($result)){
echo "<tr>";
echo "<td>" . $count . "</td>";
echo "<td>" . $row['first_name'] . "</td>";
echo "<td>" . $row['last_name'] . "</td>";
echo "<td>" . $row['emp_number'] . "</td>";
echo "<td>" . $row['department'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
echo "<td>" . $row['total_printers'] . "</td>";
echo "<td>" . $row['total_scanners'] . "</td>";
echo "<td>" . $row['total_pc'] . "</td>";
echo "<td>" . $row['total_phones'] . "</td>";
echo "<td>" . $row['other_equips'] . "</td>";
echo "</tr>";
$count++;
}
echo "</table>";
echo '<div class="forscreen">';
// echo '<br />';echo '<button class="btnPrint" type="submit" value="Submit" onclick="window.print()">Print</button>';
//echo '<input type="submit" value="SAVE AS PDF" class="btnPDFsearch" name="submit"/>';
// echo '<input type="submit" value="SAVE AS PDF" class="btnPDF" name="submit" />';
echo '</div>';
echo '<div class="forscreen">';
//echo '<br />';echo '<button class="btnPrevious" type="submit" value="Submit" onclick="history.back(); return false;">Previous Page</button>';
echo '</div>';
?>
</body>
</html>
PDF code (I tried) in same file of search_empnumber:
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
include('connect-db.php');
?>
<?php
//if($_POST['submit']){
if (isset($_POST['submit'])){
require_once 'includes/practice.php';
$pdf->SetFont('times', '', 11);
$tb1 = '</br></br>
<table cellspacing="0" cellpadding="5" border="1">
<tr style="background-color:#f7f7f7;color:#333; ">
<td width="60">First Name</td>
<td width="60">Last Name</td>
<td width="80">Employee Number</td>
<td width="80">Department</td>
<td width="60">Email</td>
<td width="80">Total Printers</td>
<td width="80">Total Scanners</td>
<td width="60">Total PCs</td>
<td width="60">Total Phones</td>
<td width="60">Other Equipments</td>
</tr>
</table>';
include('connect-db.php');
//$emp_id =($_POST['emp_id']);
$emp_id =($_POST['employeenumber']);
$result1= mysql_query("SELECT * FROM employees where emp_number = '".$emp_id."'");
while($row = mysql_fetch_assoc($result1)){
$tb2 = '<table cellspacing="0" cellpadding="5" border="1">
<tr>
<td width="60">' . $row['first_name'] . '</td>
<td width="60">' . $row['last_name'] . '</td>
<td width="80">'. $row['emp_number'] .'</td>
<td width="80">'.$row['department'].'</td>
<td width="60">'.$row['email'].'</td>
<td width="80">'.$row['total_printers'].'</td>
<td width="80">'.$row['total_scanners'].'</td>
<td width="60">'.$row['total_pc'].'</td>
<td width="60">'.$row['total_phones'].'</td>
<td width="60">'.$row['other_equips'].'</td>
</tr>
</table>';
$tb1 = $tb1.$tb2;
}
$pdf->writeHTML($tb1, true, false, false, false, '');
ob_end_clean();
$pdf->Output('Report.pdf', 'D');
}
?>
The files i.e. practoce.php and pdf libraries are not added becuase they are just creating tables in defined formats
You are mixing up GET and POST. Try one (or both) of the following:
1) In the dropdown code, replace <form> with:
<form method="POST">
2) In the table generation code, read the value back with:
$emp_id =($_REQUEST['employeenumber']);
and also:
if (isset($_REQUEST['submit'])){
To add to your problems, in the first version of search_empnumber.php you posted, you read back $emp_id =($_REQUEST['emp_id']); when the posted value will actually be in $_REQUEST['employeenumber'].
I don't know which part is going wrong for you, but there's some strange things going on in that dropdown code:
<select name="employeenumber" class="input" onchange="showUser(this.value)">
<option value="">Please Select Employee Number:</option>
</div> <!-- ISSUE: Closed a div which was never opened. You're lucky the select box even shows anything-->
<?php
$select_emp="SELECT distinct(emp_number) FROM employees";
$run_emp=mysql_query($select_emp);
//ISSUE: You loop through a lot of data, but then do nothing with it. With every pass of the loop, you simply change the variables, and nothing else. I think you meant to move your <option> into the loop
while($row=mysql_fetch_array($run_emp)){
//ISSUE: You only selected 'emp_number' in your query. Most of these array keys are never filled
$emp_id=$row['emp_id'];
$first_name=$row['first_name'];
$last_name=$row['last_name'];
$emp_number=$row['emp_number']; //This is the only one filled
$total_printers=$row['total_printers'];
$total_scanners=$row['total_scanners'];
$total_pc=$row['total_pc'];
$total_phones=$row['total_phones'];
$other_equips=$row['other_equips'];
?>
<!--ISSUE: Only the last $emp_number from the query is filled. The rest you kept overwriting in your loop-->
<option value="<?php echo $emp_number;?>"><?php echo $emp_number;?></option>
<?php } ?>
</select>

Table row populated by drop down selection

i have a drop down list populated from a database(it is the first cell in a table row) then based on that selection i want it to populate the rest of the row from the same database, each cell is a different table in the database, so far i only have it populating the first cell (calories), i can't figure out how to get it to populate the rest of the cells, thanks
<?php
$link=mysqli_connect("localhost", "root", "");
mysqli_select_db($link,"meal_planner");
?>
<!DOCTYPE html>
<html>
<head>
<title>Meal Planner</title>
<link href="main2.css" rel="stylesheet" type="text/css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function($){
// Hide all panels to start
var panels = $('.accordion > dd').hide();
// Show first panel on load (optional). Remove if you want
panels.first().show();
// On click of panel title
$('.accordion > dt > a').click(function() {
var $this = $(this);
// Slide up all other panels
panels.slideUp();
//Slide down target panel
$this.parent().next().slideDown();
return false;
});
});
</script>
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<dl class="accordion">
<dt>Monday</dt>
<dd>
<table>
<tr>
<th>Breakfast</th>
<th>Calories</th>
<th>Protein</th>
<th>Carbs</th>
<th>Fat</th>
<th>Serving Sizing</th>
</tr>
<tr>
<td>
<select name="breakfa"s onchange="showUser(this.value)">
<option value="">Select a Protein:</option>
<?php
$res=mysqli_query($link,"select name, protein_id from protein");
while($row=mysqli_fetch_array($res))
{
?>
<option value="<?php echo $row["protein_id"]; ?>"><?php echo $row["name"]; ?></option>
<?php
}
?>
</select>
</td>
<td><div id="txtHint"><b>0</b></div></td>
<td>50</td>
<td>50</td>
<td>50</td>
<td><input type="" name=""></td>
</tr>
</table>
</dd>
<dt>Tuesday</dt>
<dd>TEST</dd>
<dt>Wednesday</dt>
<dd>TEST.</dd>
</dl>
</body>
</html>
php
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('localhost','root','','meal_planner');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
$sql="SELECT * FROM protein WHERE protein_id = '".$q."'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['calories'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>

Categories