Display Table Results Based on Dropdown Selection - php

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()) { ?>

Related

import csv in mysql db using ajax and php

i was working on a mini project that imports csv file to the database through ajax and it's working fine.
here are my files
<?php
// creating database connection , executing queries and storing results
$connect = mysqli_connect("localhost","root", "", "dbname" );
$query = "SELECT * FROM csv ORDER BY id desc ";
$result = mysqli_query($connect, $query);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Marks Statistics</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js">
</script>
</head>
<body>
<br/><br/>
<div class="container", style="width: 1000px;">
<h3 align="center">CSV DATABASE</h3><br/>
<!-- creating upload form -->
<form id="upload_csv" method="post" enctype="multipart/form-data">
<div class="col-md-3">
<label>Upload More Files</label>
</div>
<div class="col-md-4">
<input type="file" name="marks_file" />
</div>
<div class="col-md-5" >
<input type="submit" name="upload" id="upload" value="upload" class="btn btn-info">
</div>
<div style= "clear:both"></div>
</form>
<br/><br/><br/>
<!-- HTML table to display contents of the csv file -->
<div class="table-responsive" id="marks_table">
<table class="table table-bordered">
<tr>
<th width="25%" >name</th>
<th width="15%" >Physics</th>
<th width="15%" >Maths</th>
<th width="15%" >Chemistry</th>
<th width="15%" >Biology</th>
<th width="15%" >SST</th>
</tr>
<?php
while ($row = mysqli_fetch_array($result))
{
?>
<!-- append row data into table -->
<tr>
<td><?php echo $row["name"]; ?> </td>
<td><?php echo $row["Physics"]; ?> </td>
<td><?php echo $row["Maths"]; ?> </td>
<td><?php echo $row["Chemistry"]; ?> </td>
<td><?php echo $row["Biology"]; ?> </td>
<td><?php echo $row["SST"]; ?> </td>
<?php
}
?>
</table>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$('#upload_csv').on("submit", function(e){
e.preventDefault(); //form will not submitted
$.ajax({
url:"export.php",
method:"POST",
data:new FormData(this),
contentType:false, // The content type used when sending data to the server.
cache:false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data){
if(data=='errorx')
{
alert("Invalid File");
}
else if(data == "errory")
{
alert("Please Select File");
}
else
{
$('#marks_table').html(data);
}
}
})
});
});
</script>
And
//export.php
<?php
if(!empty($_FILES["marks_file"]["name"]))
{
$connect = mysqli_connect("localhost", "root", "", "dbname");
$output = '';
$allowed_ext = array("csv");
$extension = end(explode(".", $_FILES["marks_file"]["name"]));
if(in_array($extension, $allowed_ext))
{
$file_data = fopen($_FILES["marks_file"]["tmp_name"], 'r');
fgetcsv($file_data);
while($row = fgetcsv($file_data))
{
$name = mysqli_real_escape_string($connect, $row[0]);
$Physics = mysqli_real_escape_string($connect, $row[1]);
$Maths = mysqli_real_escape_string($connect, $row[2]);
$Chemistry = mysqli_real_escape_string($connect, $row[3]);
$Biology = mysqli_real_escape_string($connect, $row[4]);
$SST = mysqli_real_escape_string($connect, $row[5]);
$query = "
INSERT INTO csv
(name, Physics, Maths, Chemistry, Biology, SST)
VALUES ('$name', '$Physics', '$Maths', '$Chemistry', '$Biology' , '$SST')
";
mysqli_query($connect, $query);
}
$select = "SELECT * FROM csv ORDER BY id DESC";
$result = mysqli_query($connect, $select);
$output .= '
<table class="table table-bordered">
<tr>
<th width="25%" >name</th>
<th width="15%" >Physics</th>
<th width="15%" >Maths</th>
<th width="15%" >Chemistry</th>
<th width="15%" >Biology</th>
<th width="15%" >SST</th>
</tr>
';
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td>'.$row["name"].'</td>
<td>'.$row["Physics"].'</td>
<td>'.$row["Maths"].'</td>
<td>'.$row["Chemistry"].'</td>
<td>'.$row["Biology"].'</td>
<td>'.$row["SST"].'</td>
</tr>
';
}
$output .= '</table>';
echo $output;
}
else
{
echo 'errorx';
}
}
else
{
echo "errory";
}
?>
however the imported csv files inserts null values in the tables
because the format of all csv files assigned to me are in the exact same format:
,,,,,,,,
,,,,,,,,
,,,,,,,,
,,,,,,,,
,,,,,,,,
,,,,,,,,
,,,,,,,,
,,,,,,,,
,,,,,,,,
,,,Fields,Physics~75,Maths~50,Chemistry~65,Bio~85,SST~100
,,,Name1,10,25,35,42,62
,,,Name2,80,45,45,45,25
,,,Name3,63,25,63,36,36
,,,Name4,82,36,75,48,42
,,,Name5,45,45,78,25,24
,,,Name6,36,36,15,75,36
,,,Name7,99,45,24,24,45
,,,Name8,45,85,85,85,96
i've tried multiple escape functions but none works, and it gets difficult to remove the fields line also.
For this:
csv files inserts null values in the tables
,,,,,,,,
,,,,,,,,
Check empty Like this (after filtering the array):
while($row = fgetcsv($file_data)) //['','','','','']
{
if(empty(array_filter($row))) continue; //[] after array_filter
///...
}
For the Fields one you do essentially the same thing, except in the condition look for something like
while($row = fgetcsv($file_data)) //['','','','','']
{
if(empty(array_filter($row)) || $row[3]=='Fields') continue; //[] after array_filter
///...
}
You can just look for empty($row[3]) but that is only telling you that column is empty, not the whole row.
UPDATE
I figured it out , it was a silly indexing error in my code considering the type of csv files i have.
If you want Associate arrays, with the keys from the header it can be very easy to do: If the headers are correct and the rows have the correct number of columns, and the names of the headers are unique:
$headers = fgetcsv($file_data); //['header1','header2']
while($data = fgetcsv($file_data)) //['data1','data2']
{
$row = array_combine($headers,$data); //['header1'=>'data1','header2'=>'data2']
Array combine Must have the same number of keys as values to work (both arrays must be the same length). In a typical CSV this "should" always be the case, in my experience it's not. However, when it's not that row is suspect to having it's data shifted to the wrong columns (under normal circumstances, without array combine). So you have to ask yourself if your ok with that.
Anyway hope it helps.
I figured it out , it was a silly indexing error in my code considering the type of csv files i have.
i added
if ($row[3]=='Fields' || $row[3]=='') continue;
and it worked.

autocomplete input with database record

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>

How should i be including my json codes in my php file and html file

Currently these are my codes. My php page:
$con = mysqli_connect($host, $username, $password, $db_name);
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
$sql = "SELECT problem.id, problem.DateTimeCreated, status.status_desc, users.username FROM problem
JOIN issue ON problem.issue_id = issue.id
JOIN status ON problem.status = status.id
JOIN users ON problem.reported_account_id = users.id
where issue_id = '3'";
$result = mysqli_query($con,$sql);
echo '<table width="200" border="0" cellpadding="0" cellspacing="0">';
echo "<table>
<tr>
<th>Unique ID</th>
<th>Date</th>
<th>Status</th>
<th>Reported by</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['DateTimeCreated'] . "</td>";
echo "<td>" . $row['status_desc'] . "</td>";
echo "<td>" . $row['username'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
My html code:
<script>
function display(){
var xmlhttp = new XMLHttpRequest();
var url = serverURL() + "/gwifiv2.php";
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
</script>
</head>
<body>
<div data-role="page" data-theme="a">
<div data-role="header" data-position="inline">
<br>
<h1>Issues</h1>
<br>
</div>
<div data-role="content" data-theme="a">
<div data-role="main" class="ui-content">
<table data-role="table" data-mode="columntoggle" class="ui-responsive ui-shadow" id="myTable">
<thead>
<form>
<input type="button" value="Display" onclick="display()">
</form>
<tr>
<th>Unique ID</th>
<th data-priority="1">Date</th>
<th data-priority="2">Status</th>
<th data-priority="3">Ticket</th>
</tr>
</thead>
I am unable to display my php table gotten from the database on my html code. If I directly type in the url for my php page, it will display the table, but when I insert my codes into my andriod device the table does not display.
You have to define a div or something where to display server's response on click. I have slightly modify your JavaScript and HTML to render AJAX response properly.
Here is the modified html
<script>
function display(){
var xmlhttp = new XMLHttpRequest();
var url = serverURL() + "/gwifiv2.php";
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("test").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
</script>
</head>
<body>
<div data-role="page" data-theme="a">
<div data-role="header" data-position="inline">
<br>
<h1>Issues</h1>
<br>
</div>
<div data-role="content" data-theme="a">
<div data-role="main" class="ui-content">
<table data-role="table" data-mode="columntoggle" class="ui-responsive ui-shadow" id="myTable">
<thead>
<form>
<input type="button" value="Display" onclick="display()">
<div id="test"></div>
</form>
<tr>
<th>Unique ID</th>
<th data-priority="1">Date</th>
<th data-priority="2">Status</th>
<th data-priority="3">Ticket</th>
</tr>
</thead>

table with pagination populated by drop down

im working on a page that populates a drop down menu, from an sql query to show vehicles that belong to a certain user. once a vehicle is selected it runs a function that opens a table with invoices tied to that vehicle. the problem is the number of invoices is rather large and i would like to use pagination to move forward and backwards through them. so far, it brings up the first page just fine. when i click next it gives me an error saying undefined index q and it also looses all my html formatting, most likely because in forwards to my getuser.php page. please take a look at my code and tell me what im doing wrong, ive been trying to get this to work for hours
source code for securedpage.php
<?php
include('config.inc');
include('func.inc.php');
include('db.inc.php');
$hostname = 'localhost'; // Your MySQL hostname. Usualy named as 'localhost', so you're NOT necessary to change this even this script has already online on the internet.
$dbname = 'ServiceHistoryDB'; // Your database name.
$username = 'root'; // Your database username.
$password = ''; // Your database password. If your database has no password, leave it empty.
// Let's connect to host
mysql_connect($hostname, $username, $password) or DIE('Connection to host is failed, perhaps the service is down!');
// Select the database
mysql_select_db($dbname) or DIE('Database name is not available!');
// This could be supplied by a user, for example
$username = $_SESSION['username'];
// Formulate Query
// This is the best way to perform an SQL query
// For more examples, see mysql_real_escape_string()
$query = sprintf("SELECT * FROM customers
WHERE username='%s'",
mysql_real_escape_string($username));
// Perform Query
$result = mysql_query($query);
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
// Use result
// Attempting to print $result won't allow access to information in the resource
// One of the mysql result functions must be used
// See also mysql_result(), mysql_fetch_array(), mysql_fetch_row(), etc.
while ($row = mysql_fetch_assoc($result)) {
echo $row['CustNum'];
$custnum = $row['CustNum'];
}
// Free the resources associated with the result set
// This is done automatically at the end of the script
mysql_free_result($result);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Arndt Automotive</title>
<style type="text/css">
body {
background-image: url(Background.png);
}
</style>
</head>
<body>
<table width="1050" border="0" align="center">
<tr align="center">
<td><img src="Banner.png" width="1050" height="275" alt="Banner" /></td>
</tr>
</table>
<table width="1200" height="638" border="0" align="center" background="backgroundmaybe2.png" " style="background-repeat: no-repeat; background- position: center;>
<tr align="center">
<td><table width="1090" height="638" border="0" align="center">
<tr align="left">
<td width="225"><table width="225" height="638" border="0" id="Left">
<tr>
<td align="center" valign="top" background="backgroundtable1.png"><p> </p>
<p><img src="Home.png" width="170" height="30" alt="Home" /></p>
<p><img src="About Us.png" width="170" height="30" alt="About Us" /></p>
<p><img src="Services.png" width="170" height="30" alt="Services" /></p>
<p><img src="Recent Work.png" width="170" height="30" alt="Recent Work" /></p>
<p><img src="My Account.png" width="170" height="30" alt="My Account" /></p>
<p><img src="Contact Us.png" width="170" height="30" alt="Contact Us" /></p>
<p><img src="Promotions.png" width="170" height="30" alt="Promotions" /></p>
<p><img src="Location.png" width="170" height="30" alt="Location" /></p>
<p><img src="Hours.png" width="170" height="150" alt="Hours" /></p></td>
</tr>
</table></td>
<td width="125"> </td>
<td width="850"><table width="850" height="638" border="0" background="backgroundtable2.png" >
<tr>
<td align="center"><html>
<head>
<title></title>
<script>
function showUser(str)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
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>
<body>
<?php echo $username?></b>
<?php echo $custnum?></b>
<form>
<select name="dropdown" onChange="showUser(this.value)">
<?php query() ;
?>
</select>
<?php close() ?>
</form>
<div id="txtHint"><b>Invoice info will be listed here.</b></div></td>
<p>Logout</p>
</tr>
</table></td>
</tr>
</table></td>
</tr>
</table>
<table width="1050" height="275" border="0" align="center" background="Footer.png">
<tr>
<td><table width="950" border="0" align="center">
<tr>
<td width="256" align="left"><img src="AC Delco Logo.png" width="245" height="47" alt="AC Delco" /></td>
<td width="265" align="center"><img src="ASA Logo.png" width="248" height="115" alt="ASA" /></td>
<td width="141" align="center"><img src="ASE Logo.png" width="112" height="115" alt="ASE" /></td>
<td width="270"><img src="Jasper Logo.png" width="252" height="81" alt="Jasper" /></td>
</tr>
</table></td>
</tr>
</table>
<p> </p>
</body>
</html>
and this is the source code for getuser.php
<?PHP
// Connects to your Database
mysql_connect('localhost', 'root') or die(mysql_error());
mysql_select_db("ServiceHistoryDB") or die(mysql_error());
$q=$_GET["q"];
//This checks to see if there is a page number. If not, it will set it to page 1
if (!(isset($pagenum)))
{
$pagenum = 1;
}
//Here we count the number of results
//Edit $data to be your query
$data = mysql_query("SELECT * FROM invoices") or die(mysql_error());
$rows = mysql_num_rows($data);
//This is the number of results displayed per page
$page_rows = 10;
//This tells us the page number of our last page
$last = ceil($rows/$page_rows);
//this makes sure the page number isn't below one, or more than our maximum pages
if ($pagenum < 1)
{
$pagenum = 1;
}
elseif ($pagenum > $last)
{
$pagenum = $last;
}
//This sets the range to display in our query
$max = 'limit ' .($pagenum - 1) * $page_rows .',' .$page_rows;
//This is your query again, the same one... the only difference is we add $max into it
$data_p = mysql_query("SELECT * FROM invoices WHERE CarNum = '".$q."' $max") or die(mysql_error());
//This is where you display your query results
echo "<table border='1'>
<tr>
<th>Date</th>
<th> Service </th>
</tr>";
while($info = mysql_fetch_array( $data_p ))
{ echo "<tr>";
echo "<td>" .date('M d Y', strtotime($info['Date'])) . "</td>";
echo "<td>" . $info['BriefDescription'] . "</td>";
echo "<br>";
echo "</tr>";
}
echo "</table>";
// This shows the user what page they are on, and the total number of pages
// First we check if we are on page one. If we are then we don't need a link to the previous page or the first page so we do nothing. If we aren't then we generate links to the first page, and to the previous page.
if ($pagenum == 1)
{
}
else
{
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=1'> <<-First</a> ";
echo " ";
$previous = $pagenum-1;
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$previous'> <-Previous</a> ";
}
//just a spacer
echo " ---- ";
//This does the same as above, only checking if we are on the last page, and then generating the Next and Last links
if ($pagenum == $last)
{
}
else {
$next = $pagenum+1;
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$next'>Next -></a> ";
echo " ";
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$last'>Last ->></a> ";
}
?>
Try out this useful Jquery Plugin.
Jquery Plugin for data Table

Call to undefined function ProdTotal()

I am trying to call function ProdTotal to get the total quantity order and total amount ordered for a product and load it in the table in the Display Function. I am getting the error: Call to undefined function ProdTotal();
<?php
Class CarsClass {
private $user = 'php06';
private $pwd = 'php06';
private $dbConn;
function __construct($db='classicmodels') {
//Create connection to MySQL database requested, if blank just connect up.
$this->dbConn = new mysqli('localhost', $this->user, $this->pwd, $db);
if (mysqli_connect_errno()) {
echo 'Error: Could not connect to database. Please try again later.';
exit;
}
$query = "select count(*) as 'custcount' from customers";
$result = $this->dbConn->query($query);
$row = $result->fetch_assoc();
$custCount = $row['custcount'];
print "Connected to DB $db as user $this->user<br><br> Number of Rows $custCount<br><br>";
}
function __destruct(){
mysqli_close();
Print "DB closed by user <br><br>";
}
function header(){
echo "Midterm Exam Script 2 Header<br><br>";
}
function display(){
$totqty = 0;
$totamt = 0;
//get row from WB_Resident Table
$query = "select productCode,productName,productDescription,quantityInStock,buyprice,MSRP from products";
$result = $this->dbConn->query($query);
?>
<table id="midterm2">
<tr>
<th colspan="13">Product Database Table</th>
</tr>
<tr>
<th width="2%">productCode</th>
<th width="10%">productName</th>
<th width="10%">productDescription</th>
<th width="10%">quantity in stock</th>
<th width="10%">buyPrice</th>
<th width="2%">MSRP</th>
<th width="10%">Total Qty Ordered</th>
<th width="10%">Total $ Ordered</th>
</tr>
<?php
while($row = $result->fetch_assoc()):
$producta = $row["productCode"];
ProdTotal($producta);
?>
<tr>
<td>
<?php echo $row["productCode"]; ?>
</td>
<td>
<?php echo $row["productName"];?>
</td>
<td>
<?php echo $row["productDescription"]; ?>
</td>
<td>
<?php echo $row["Qty In Stock"]; ?>
</td>
<td>
<?php echo $row["Buy Price"]; ?>
</td>
<td>
<?php echo $row["MSRP"]; ?>
</td>
<td>
<?php echo $totqty; ?>
</td>
<td>
<?php echo $totamt; ?>
</td>
</tr>
<?php
endwhile;
?>
</table>
<?php
}
function footer(){
echo "Midterm Exam Script 3 Footer<br><br>";
}
function ProdTotal($product){
echo "product code entered = $product <br><br>";
$query = "select RTRIM(productCode) as productt, quantityOrdered, priceEach from orderdetails order by productt";
$result = $this->dbConn->query($query);
while($row = $result->fetch_assoc()){
if ($row["productt"] == $product){
echo $row;
$total = $row["quantityOrdered"] * $row["priceEach"];
$totqty = $totqty + $row["quantityOrdered"];
$totamt = $totamt + $total;
echo totqty;
echo totamt;
return array($totqty, $totamt);
}
}
}
}
?>
This script is executed to call class.
<html>
<head>
<title>Midterm2 Script 3</title>
<link rel="stylesheet" type="text/css" href="midterm2.css" />
</head>
<body>
<?php
require 'CarsClass3a.php';
$obj1= new CarsClass('classicmodels');
$obj1->header();
$obj1->display();
$obj1->footer();
?>
</body>
</html>
In display(), change the call to ProdTotal() to
list($totqty, $totamt) = $this->ProdTotal($producta);

Categories