Ajax responsetext as a table output? - php

I'm not really familiar with Ajax Response - I have edited the PHP Ajax Search code from W3schools.com as follows :
<?php
require_once('connect_db.php');
$query = "select item_no from items";
$result = mysql_query($query);
$a = array();
while ($row = mysql_fetch_assoc($result)){
$a[] = $row['item_no'];
}
//get the q parameter from URL
$q=$_GET["q"];
//lookup all hints from array if length of q>0
if (strlen($q) > 0)
{
$hint="";
for($i=0; $i<count($a); $i++)
{
if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q))))
{
if ($hint=="")
{
$hint=$a[$i];
}
else
{
$hint=$hint." , ".$a[$i];
}
}
}
}
// Set output to "no suggestion" if no hint were found
// or to the correct values
if ($hint == "")
{
$response="No Suggestion";
}
else
{
$response=$hint;
}
//output the response
echo "<table border=1><tr><td>".$response."</td></tr></table>";
?>
The output of the above code works perfectly, but they are all listed like this (2L500BU , 2L500GO , 2L500NA , 2L500RD , 2L802CA , 2L802WH , 2L803GR , 2L804BE , 2L804BK , 2L804CO , 2L805BU , 2L806BE , 2L806GR ) - Those numbers are Item No in mysql table called items.
Now :
1) I want to output the response into table with <tr> for each like this
2l500BU
2L500GO
.
.
.
.
etc.
2) Do you think its possible to output all table records from Mysql based on the hint entered as follows :
$sql="SELECT * FROM items WHERE item_no = '".**$hint**."'";
$result = mysql_query($sql);
echo "<table align='center' cellpadding='3' cellspacing='3' width='800px' border='1' font style='font-family:arial;'>";
echo "
<tr align=center>
<th style=font-size:18px; bgcolor=#20c500>Item Number</th>
<th style=font-size:18px; bgcolor=#20c500>QTY</th>
<th style=font-size:18px; bgcolor=#20c500>Actual Price</th>
<th style=font-size:18px; bgcolor=#20c500>Selling Price</th>
<th style=font-size:18px; bgcolor=#20c500>Difference</th>
<th style=font-size:18px; bgcolor=#20c500>Date</th>
</tr>";
while($row = mysql_fetch_assoc($result)){
echo "<tr align=center bgcolor=#e3e3e3>";
echo "<td style='font-size:18px; font-weight:bold;'>" . strtoupper($row['item_no']) . "</td>";
echo "<td style='font-size:18px; font-weight:bold;'>" . $row['qty'] . "</td>";
echo "<td style='font-size:18px; font-weight:bold;'>" . $row['actual_price'] . " <font style=font-size:12px;>JD</font></td>";
echo "<td style='font-size:18px; font-weight:bold;'>" . $row['discount_price'] . " <font style=font-size:12px;>JD</font></td>";
echo "<td style='font-size:18px; font-weight:bold;'>" . $row['difference_price'] . " <font style=font-size:12px;>JD</font></td>";
echo "<td style='font-size:18px; font-weight:bold;'>" . date("d-m-Y",strtotime($row['date'])) . "</td>";
echo "</tr>";
}
echo "<table>";

If you're wanting to fetch items from a database and display a row for each of them, this is how you'd do it with jQuery.
Your PHP script:
<?php
$mysqli = new mysqli('localhost', 'user', 'password', 'database');
$sql = "SELECT item_no FROM items";
$res = $mysqli->query($sql);
while ($row = $res->fetch_assoc()) {
$rows[] = $row['item_no'];
}
header('Content-Type: application/json');
echo json_encode($rows);
?>
And your HTML with the table:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<table>
<thead>
<tr>
<th scope="col">Item No.</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</body>
</html>
<script src="js/lib/jquery.js"></script>
<script>
$(document).ready(function() {
$.getJSON('yourscript.php', function(items) {
$.each(items, function(i, item) {
$('tbody').append('<tr><td>' + item + '</td></tr>);
});
});
});
</script>
I've also used MySQLi (MySQL improved) rather than the standard mysql_ functions, as the mysql_ library is deprecated and you should be using either MySQLi or PDO now.

Related

how to get the content of current webpage in mpdf library

i have the below code written, actually i thought of converting the current webpage to pdf document, but i couldnt make how to declare the current url and get the contents of the webpage in pdf doc. below is my code.
<?php
require("mpdf60/mpdf.php");
$mpdf=new mPDF('utf-8','Letter-L','','',15,10,16,10,10,10);//A4 page in portrait for landscape add -L.
$mpdf->SetHeader('|Your Header here|');
$mpdf->setFooter('{PAGENO}');// Giving page number to your footer.
$mpdf->useOnlyCoreFonts = true; // false is default
$mpdf->SetDisplayMode('fullpage');
$mpdf->debug = true;
// Buffer the following html with PHP so we can store it to a variable later
ob_start();
?>
<?php
include "contractview.php?ID=129";
//This is your php page ?>
<?php
$html = ob_get_contents();
ob_end_clean();
// send the captured HTML from the output buffer to the mPDF class for processing
$mpdf->WriteHTML($html);
//$mpdf->SetProtection(array(), 'user', 'password'); uncomment to protect your pdf page with password.
$mpdf->Output();
exit;
?>
i have written include "contractview.php?ID=129"; but this was not working, can any one please help me in how to assign this to get the current page contents.
MPDF doesn't support includes. You have to put it in a var. The full html can be converted using jquery or in php with file_get_contents.
This is how i did it with full page.
<?php
require("mpdf60/mpdf.php");
$mpdf=new mPDF('utf-8','Letter-L','','',15,10,16,10,10,10);//A4 page in portrait for landscape add -L.
$mpdf->SetHeader('|Your Header here|');
$mpdf->setFooter('{PAGENO}');// Giving page number to your footer.
$mpdf->useOnlyCoreFonts = true; // false is default
$mpdf->SetDisplayMode('fullpage');
$mpdf->debug = true;
// Buffer the following html with PHP so we can store it to a variable later
ob_start();
?>
<?php
//$content = file_get_contents("contractview.php?ID=129"); //<=== WRONG ONE
$content = file_get_contents("http://www.yourwebsite.com/contractview.php?ID=129"); //<=== getting content from url and not file!!
print($content);
//This is your php page ?>
<?php
$html = ob_get_contents($content); //<=== put content in ob
ob_end_clean();
// send the captured HTML from the output buffer to the mPDF class for processing
$mpdf->WriteHTML($html);
//$mpdf->SetProtection(array(), 'user', 'password'); uncomment to protect your pdf page with password.
$mpdf->Output();
exit;
?>
I see you are using ob_start and ob_end
You coudl also use
<?php
require("mpdf60/mpdf.php");
$mpdf=new mPDF('utf-8','Letter-L','','',15,10,16,10,10,10);//A4 page in portrait for landscape add -L.
$mpdf->SetHeader('|Your Header here|');
$mpdf->setFooter('{PAGENO}');// Giving page number to your footer.
$mpdf->useOnlyCoreFonts = true; // false is default
$mpdf->SetDisplayMode('fullpage');
$mpdf->debug = true;
// Buffer the following html with PHP so we can store it to a variable later
$content = file_get_contents("http://www.yourwebsite.com/contractview.php?ID=129"); //<=== getting content from url and not file!!
// send the captured HTML from the output buffer to the mPDF class for processing
$mpdf->WriteHTML($content);
//$mpdf->SetProtection(array(), 'user', 'password'); uncomment to protect your pdf page with password.
$mpdf->Output();
exit;
?>
<?php require_once ('header.php'); ?>
<!-- 10/15/2014 START: Freze table header row; Updated Fancybox so it works with jQuery 1.10.1 as well -->
<META content="IE=11; IE=10; IE=9; IE=8; IE=7; IE=EDGE" http-equiv="X-UA-Compatible">
<!--script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script duplicate 10/6/2015-->
<SCRIPT type="text/javascript" src="jQueryfloatThead/jquery.floatThead.js"></SCRIPT>
<SCRIPT type="text/javascript" src="jQueryfloatThead/site.js"></SCRIPT>
<SCRIPT type="text/javascript" src="jQueryfloatThead/bootstrap.js"></SCRIPT>
<SCRIPT type="text/javascript" src="jQueryfloatThead/less.js"></SCRIPT>
<!-- 10/15/2014 END -->
<body bgcolor="#FFFFFF" leftmargin="0" topmargin="0" marginwidth="0" marginheight="0">
<table width="100%" border=0 cellpadding="0" cellspacing="0">
<tr><td height="36" background="images/topbar_bg.png" style="background-repeat:repeat-x;"><img src="images/topbar_bg.png" height="36"></td></tr>
<tr><td>
<table width="960" border=0 cellpadding="0" cellspacing="0" align="center">
<?php require_once ('topnav.php'); ?>
<tr><td>
<table width="100%" border=0 cellpadding="10" cellspacing="5">
<?php
if(!isset($_SESSION['Username'])) {
header('Location: home?errMsg=Your session has been expired. Please re-login again.');
}
?>
<tr><td bgcolor="#006ec7" valign="top" width="100%" class="headertd">FAR Compliance Portal</td></tr>
<tr><td bgcolor="#ebf4f9" valign="top" width="100%" height="300">
<?php
require_once ('dbconnection.php');
require_once ('contractcheck.php'); //Check if users can view this section
if (!isset($_REQUEST['ID'])) {
print "ERROR: No record has been selected.";
exit;
}
if (!is_numeric($_REQUEST['ID'])) {
print "ERROR: Invalid record has been selected.";
exit;
}
$thisID = $_REQUEST['ID'];
$sqlGet = "select * from far_contract where ID='" .$thisID. "'";
$resultGet = mysql_query($sqlGet, $dbconnection);
if (!$resultGet) {
echo 'Could not run query [1] ($thisID): ' . mysql_error();
exit;
}
$num_rows = mysql_num_rows($resultGet);
if ($num_rows==0 || $num_rows>1) {
print "Error: Invalid record is being called ($thisID). Please check with administrator.";
exit;
}
$row = mysql_fetch_array($resultGet);
$thisID = $row[0];
$thisContractNumber = $row[1];
$thisCustomer = $row[2];
$thisCeilingValue = $row[3];
//$thisEffectiveDate = $row[4];
//$thisExpirationDate = $row[5];
//$thisLegalEntity = $row[6];
$thisProjectName = $row[4];
$thisMFilesLink = $row[5];
$thisCreatedByID = $row[6];
$thisCreatedDate = $row[7];
$thisModifiedByID = $row[8];
$thisModifiedDate = $row[9];
$thisContractStatus = $row[10]; //12/22/2014
$thisNotes = $row[11]; //3/27/2015
$thisSubmittedByID = $row[17]; //10/1/2015
$thisSubmittedDate = $row[18]; //10/1/2015
$thisMasterAgreement = $row[19]; //10/6/2015
if ($thisContractStatus==NULL) $thisContractStatus="Not Submitted"; //12/22/2014
$thisSpecialStatusNotes = $row[15]; //4/15/2015
unset($resultGet);
//if ($thisEffectiveDate!="") $thisEffectiveDate = date("m/d/Y", strtotime($thisEffectiveDate));
//if ($thisExpirationDate!="") $thisExpirationDate = date("m/d/Y", strtotime($thisExpirationDate));
$sqlGetFAR = "select * from far_contract_clauses where ContractID='" .$thisID. "'";
$resultGet = mysql_query($sqlGetFAR, $dbconnection);
if (!$resultGet) {
echo 'Could not run query [2] ($thisID): ' . mysql_error();
exit;
}
$num_rows = mysql_num_rows($resultGet);
if ($num_rows>0) {
$thisSelectClause = "";
while ($row = mysql_fetch_array($resultGet)) {
if ($thisSelectClause=="")
$thisSelectClause = $row[2];
else
$thisSelectClause .= ",".$row[2];
}
}
unset($resultGet);
?>
<h1>Contract Records > View Record</h1>
<a href='php-to-pdf.php' target='_blank' ><input type='button' value='Convert to pdf'></a>
<table cellspacing=0 cellpadding=3 border=0 width="100%" class="table-bordered">
<tr>
<td class="resultTbl" bgcolor='#d9e0e4'><b>ID:</b></td>
<td class="resultTbl"><?php echo $thisID ?></td>
</tr>
<tr>
<td nowrap width="220" class="resultTbl" bgcolor='#d9e0e4'><b>Direct Customer's Solicitation/Contract Number:</b></td>
<td width="100%" class="resultTbl"><?php echo $thisContractNumber ?></td>
</tr>
<tr>
<td class="resultTbl" bgcolor='#d9e0e4'><b>Direct Customer:</b></td>
<td class="resultTbl"><?php echo $thisCustomer ?></td>
</tr>
<tr>
<td class="resultTbl" bgcolor='#d9e0e4'><b>Ceiling Value ($):</b></td>
<td class="resultTbl"><?php is_numeric($thisCeilingValue)? print "$ ".number_format($thisCeilingValue,2) : print ""; ?></td>
</tr>
<!--<tr>
<td class="resultTbl" bgcolor='#d9e0e4'><b>Effective Date:</b></td>
<td class="resultTbl"><//php echo $thisEffectiveDate //></td>
</tr>
<tr>
<td class="resultTbl" bgcolor='#d9e0e4'><b>Expiration Date:</b></td>
<td class="resultTbl"><//php echo $thisExpirationDate //></td>
</tr>
<tr>
<td class="resultTbl" bgcolor='#d9e0e4'><b>Rapiscan Legal Entity:</b></td>
<td class="resultTbl"><//php echo $thisLegalEntity //></td>
</tr>-->
<tr>
<td class="resultTbl" bgcolor='#d9e0e4'><b>Project Name/Description:</b></td><?php //3/27/2015 ?>
<td class="resultTbl"><?php echo $thisProjectName ?></td>
</tr>
<tr>
<td class="resultTbl" bgcolor='#d9e0e4'><b>M-Files Link:</b></td>
<td class="resultTbl"><?php echo $thisMFilesLink ?></td>
</tr>
<tr><?php //3/27/2015 ?>
<td class="resultTbl" bgcolor='#d9e0e4' valign='top'><b>Notes:</b></td>
<td class="resultTbl"><?php echo $thisNotes ?></td>
</tr>
<tr>
<td class="resultTbl" bgcolor='#d9e0e4'><b>Created By:</b></td>
<td class="resultTbl"><?php echo fetchFullName($thisCreatedByID) . " on " . $thisCreatedDate ?></td>
</tr>
<?php
$SubmissionDate = $thisCreatedDate; //1/6/2015
if ($thisModifiedByID!="") { ?>
<tr>
<td class="resultTbl" bgcolor='#d9e0e4'><b>Last Modified By:</b></td>
<td class="resultTbl"><?php echo fetchFullName($thisModifiedByID) . " on " . $thisModifiedDate ?></td>
</tr>
<?php
$SubmissionDate = $thisModifiedDate; //1/6/2015
}
?>
<?php
$SubmittedDate = $thisSubmittedDate; //10/1/2015 Added Submitted By and Submitted Date
if ($thisSubmittedByID!="") { ?>
<tr>
<td class="resultTbl" bgcolor='#d9e0e4'><b>Submitted By:</b></td>
<td class="resultTbl"><?php echo fetchFullName($thisSubmittedByID) . " on " . $thisSubmittedDate ?></td>
</tr>
<?php
$SubmittedDate = $thisSubmittedDate; //10/1/2015
}
?>
<?php
$MasterAgreement = $thisMasterAgreement; //10/1/2015 Added Submitted By and Submitted Date
?>
<tr>
<td class="resultTbl" bgcolor='#d9e0e4'><b>Master/Framework<b>Agreement Contract</b></td>
<td class="resultTbl"><?php echo ($thisMasterAgreement==1)?'Yes':'No'; ?></td>
</tr>
<?php
?>
<tr>
<td class="resultTbl" bgcolor='#d9e0e4'><b>Status:</b></td>
<td class="resultTbl"><?php echo $thisContractStatus //12/22/2014 ?>
<?php //4/15/2015
if ($AllowContractFull) {
if ($thisContractStatus=="Submitted") {
print " ";
print "[Suspend]";
print " [Cancel]";
} elseif ($thisContractStatus=="Suspended") {
print " ";
print "[Re-activate]";
print " [Cancel]";
}
}
if (! ($thisSpecialStatusNotes=="" || is_null($thisSpecialStatusNotes)) ) {
print "<BR><font color=gray>$thisSpecialStatusNotes</font>";
}
?>
</td>
</tr>
<tr><td valign=top colspan=2 class="resultTbl"><b>FAR Clauses:</b></td></tr>
<tr><td valign=top colspan=2 class="resultTbl">
<?php
//get list of departments
$sql = "select * from far_departments order by Department";
$result = mysql_query($sql, $dbconnection);
if (!$result) {
echo 'Could not run query [3]: ' . mysql_error();
exit;
}
$deptList = array();
while ($row = mysql_fetch_array($result)) { //loop each department
$deptList[] = $row[1];
}
unset ($result);
printByCompliance ($thisID, $thisSelectClause, $thisContractStatus, $SubmissionDate); //1/6/2015
?>
</td>
</tr>
</table>
<?php
require_once ('logging.php'); //7/31/2014
mysql_close($dbconnection);
?>
</td></tr>
</table>
</td></tr>
<?php require_once ('footer.php'); ?>
</table>
</td></tr>
</table>
</body>
</html>
<?php
function printByCompliance ($thisID, $thisSelectClause, $thisContractStatus, $SubmissionDate){ //1/6/2015
global $deptList;
global $dbconnection;
//print table header
//echo "<h1>Compliance Report</h1>";
echo "<DIV id='options'><table width='100%' class='table table-bordered table-striped' cellspacing=0 cellpadding=5>";
echo "<thead><tr bgcolor='#d9e0e4'>";
echo "<th class='resultTbl' nowrap><b>FAR Clauses</b><img src='images/spacer.gif' width='80' height='1'></th>"; //9/15/2014
if ($thisContractStatus=="Submitted" || $thisContractStatus=="Suspended" || $thisContractStatus=="Cancelled") //4/15/2015
echo "<th class='resultTbl' nowrap><font color=blue><b>Certified<BR>as of<BR>".str_replace(" ", "<BR>", $SubmissionDate)."?</b></font></th>"; //1/6/2015
else
echo "<th class='resultTbl' nowrap><font color=blue><b>Certified?</b></font></th>"; //9/15/2014
foreach ($deptList as $EachDept) { //loop each dept
echo "<th class='resultTbl' align=center><b>" . $EachDept . "</b></th>";
}
echo "</tr></thead>"; //10/15/2014 END
//get all questions
$sql = "select * from far_questions where QStatus='ACTIVE' and ID in ($thisSelectClause) order by Title, Alternate"; //2/9/2015
$result = mysql_query($sql, $dbconnection);
if (!$result) {
echo 'Could not run query [4]: ' . mysql_error();
exit;
}
$listQuestionArray = array(); //START natural-order sorting questions by title
while ($row = mysql_fetch_array($result)) {
$listQuestionArray[] = array($row[0], $row[1], $row[2], $row[3], $row[4], $row[5], $row[6], $row[7]); //2/9/2015; 10/10/2014; 6/17/2014
}
usort($listQuestionArray, function ($elem1, $elem2) {
return strnatcmp ($elem1['1']." ".$elem1['7'], $elem2['1']." ".$elem2['7']);
//2/9/2015 need to take Alternate in nartural sort*** return strnatcmp ($elem1['1'], $elem2['1']);
});
unset($row); //END natural-order sorting questions by title
foreach ($listQuestionArray as $row) { //loop each question
$thisQuestionID = $row[0];
$thisTitle = trim($row[1]);
$thisURL = trim($row[2]);
$thisVersionDate = trim($row[3]);
$thisFrequency = trim($row[4]); //6/17/2014
$thisClauseType = trim($row[6]); //10/10/2014
$thisAlternate = trim($row[7]); //2/9/2015
$RequireDepartment = ""; //6/17/2014 START new tbl structure
if ($thisClauseType=="YELLOW") { //10/10/2014
$sqlgetdept = "select RequireDepartment from far_yellowDept where QuestionID='$thisQuestionID'";
} else {
$sqlgetdept = "select RequireDepartment from far_questionsDept where QuestionID='$thisQuestionID'";
} //10/10/2014
$resultgd = mysql_query($sqlgetdept, $dbconnection);
if (!$resultgd) {
echo 'Could not run query [6]: ' . mysql_error();
exit;
}
while ($rowgd = mysql_fetch_array($resultgd)) {
$RequireDepartment .= $rowgd[0] . ", ";
}
unset ($rowgd);
unset ($resultgd);
//$RequireDepartment = trim($row[5]);
//$thisFrequency = trim($row[6]); //6/17/2014 END
$curClauseInfo = ""; //9/15/2014 temp string for Clause info
$curClauseInfo .= "<td class=resultTbl bgcolor=#d9e0e4><a class='rptnav' href='" .$thisURL. "' target=new>" . $thisTitle . "</a>";
if ($thisVersionDate!="" && $thisVersionDate != NULL) {
$curClauseInfo .= "<BR>(" .$thisVersionDate. ")";
}
if ($thisAlternate!="" && $thisAlternate != NULL) { //2/9/2015
$curClauseInfo .= "<BR><BR>" .$thisAlternate;
}
$curStatusStr = ""; //9/15/2014 temp string to store current status for each dept for current FARS clause
$chkQuestion = true; //assume this question is compliance.
foreach ($deptList as $EachDept) { //loop each dept
if (strpos($RequireDepartment, $EachDept) !== false) { //if this question is required for current dept
$curStatusStr .= "<td class=resultTbl nowrap align=center>";
if ($thisClauseType=="YELLOW") { //10/10/2014
//12/11/2014 fetch approval status for YELLOW clause from new table
$sqlConApp = "select * from far_contract_approval where ContractID='$thisID' and QuestionID='$thisQuestionID' and Department='{$EachDept}'";
$resultConApp = mysql_query($sqlConApp, $dbconnection);
if (!$resultConApp) {
echo 'Could not run query [7]: ' . mysql_error();
exit;
}
$num_rowsConApp = mysql_num_rows($resultConApp);
if ($num_rowsConApp>0) { //if approval response is found
$rowConApp = mysql_fetch_array($resultConApp);
$curStatusStr .= "<B>Approved By</B><BR>" . fetchFullName($rowConApp[4]) . "<BR>" . str_replace(" ", "<BR>", $rowConApp[5]);
} else { //if NO approval response is found
$curStatusStr .= "Approval<BR>Required";
}
unset($resultConApp); //12/11/2014
$curStatusStr .= "</td>";
$chkQuestion=false;
} else { //10/10/2014 for clause type = CERTIFY and GREEN
//check for approval
$sqlConApp = "select * from far_contract_approval where ContractID='$thisID' and QuestionID='$thisQuestionID' and Department='{$EachDept}'";
$resultConApp = mysql_query($sqlConApp, $dbconnection);
if (!$resultConApp) {
echo 'Could not run query [7b]: ' . mysql_error();
exit;
}
$num_rowsConApp = mysql_num_rows($resultConApp);
if ($num_rowsConApp>0) { //if approval response is found
$rowConApp = mysql_fetch_array($resultConApp);
$curStatusStr .= "<B>Approved By</B><BR>" . fetchFullName($rowConApp[4]) . "<BR>" . str_replace(" ", "<BR>", $rowConApp[5]);
} else {
//get latest response per each question
$sql2 = "select * from far_responses where QuestionID=$thisQuestionID and Department='{$EachDept}' order by ResponseDate desc limit 1";
$result2 = mysql_query($sql2, $dbconnection);
if (!$result2) {
echo 'Could not run query [8]: ' . mysql_error();
exit;
}
$num_rows2 = mysql_num_rows($result2);
if ($num_rows2>0) { //if response is found
$row2 = mysql_fetch_array($result2);
$thisResponse = $row2[2];
$thisResponseBy = $row2[5];
$thisResponseDate = $row2[6];
$tempResponseDate = str_replace(" ", "<BR>", $thisResponseDate); //6/12/2014 show time on next line
$curStatusStr .= "<B>". $thisResponse . "</B><BR>" . $thisResponseBy . "<BR>" . $tempResponseDate;
if ($thisResponse=="YES") { //if latest response is YES, check if it has expired or not
/* 6/2/2014 Disable this function - no need to check Frequency as all answers will be reset on 1/1
$chkDate = strtotime($thisResponseDate);
$chkDate = strtotime("+$thisFrequency day", $chkDate);
if (time() > $chkDate) {
print "<font color=red><BR>Expired</font>";
$chkQuestion=false;
}
6/2/2014 */
} else { //PENDING or EXPIRED
$chkQuestion=false;
}
} else { //no previous submission
$curStatusStr .= "Response<BR>Pending";
$chkQuestion=false;
}
}
unset($resultConApp); //12/11/2014
$curStatusStr .= "</td>";
} //10/10/2014
} else { //this question does not apply to current dept
$curStatusStr .= "<td class=resultTbl align=center>N/A</td>";
}
}
$curStatusBox = ""; //9/15/2014 temp string to store green/red icon
$curStatusBox .= "<td class=resultTbl align=center bgcolor=#d9f1fe>";
if ($thisContractStatus=="Submitted" || $thisContractStatus=="Suspended" || $thisContractStatus=="Cancelled") { //4/15/2015; 1/6/2015 Contract has been submitted
$sqlFreezeStat = "select LightIndicator from far_contract_clauses where ContractID='$thisID' and QuestionID='$thisQuestionID'";
$resultFreezeStat = mysql_query($sqlFreezeStat, $dbconnection);
if (!$resultFreezeStat) {
echo 'Could not run query [10]: ' . mysql_error();
exit;
}
$num_rowsFS = mysql_num_rows($resultFreezeStat);
if ($num_rowsFS>0) { //if response is found
$rowFS = mysql_fetch_array($resultFreezeStat);
switch ($rowFS[0]) {
case "GREEN": $curStatusBox .= "<img src='images/greenicon.gif' width='20'>"; break;
case "YELLOW": $curStatusBox .= "<img src='images/yellowicon.gif' width='20'>"; break;
case "RED": $curStatusBox .= "<img src='images/redicon.gif' width='20'>"; break;
default: $curStatusBox .= "Status is not being frozen for this record";
}
} else { $curStatusBox .= "Status is not being frozen for this record"; }
unset ($resultFreezeStat);
} else { //1/6/2015: Not submitted - so shows real-time light status
if ((int)$chkQuestion==1) {
$curStatusBox .= "<img src='images/greenicon.gif' width='20'>";
//9/15/2014 Latest Audit Info
/* 12/11/2014 hide audit *** (if want to add it back, need to add fancybox script ***
$sqlchkAudit = "select AuditDate from far_audit where QuestionID=$thisQuestionID order by AuditDate Desc limit 1";
$resultA = mysql_query($sqlchkAudit, $dbconnection);
if (!$resultA) {
echo 'Could not run query [9]: ' . mysql_error();
exit;
}
$num_rowsA = mysql_num_rows($resultA);
if ($num_rowsA >0) { //if response is found
$rowA = mysql_fetch_array($resultA);
$AuditDateTemp = $rowA[0];
$AuditDateSplit = explode(" ", $AuditDateTemp);
$AuditDate = "<a class=\"fancybox\" href=\"audithistory.php?ID=" .$thisQuestionID. "\">" .$AuditDateSplit[0]. "</a>";
//$AuditDate = $AuditDateSplit[0];
} else {
$AuditDate = "N/A";
}
$curClauseInfo .= "<BR><BR>Last Audit: " . $AuditDate;
if($_SESSION['UserAccessLevel']=="FULLAUDIT") //9/15/2014 new access level AUDIT rights
$curClauseInfo .= "<BR>Auditor: <a class=\"fancybox\" href=\"audit.php?ID=" .$thisQuestionID. "\">Audit It</a></td>";
else
$curClauseInfo .= "</td>";
hide audit*** */
} elseif ($thisClauseType=="YELLOW") { //10/10/2014
$curStatusBox .= "<img src='images/yellowicon.gif' width='20'>";
$curClauseInfo .= "</td>";
} else {
$curStatusBox .= "<img src='images/redicon.gif' width='20'>";
$curClauseInfo .= "</td>";
}
}
$curStatusBox .= "</td>";
print "<tr>"; //9/15/2014 Print out new temp strings
print $curClauseInfo;
print $curStatusBox;
print $curStatusStr;
print "</tr>";
}
echo "</table></div>"; //10/15/2014 closing DIV, added document ready
?>
<SCRIPT type="text/javascript">
$(document).ready(function () {
$('#options table').floatThead({
//the pageTop is a global function i have here, it takes care of making the table float under my floated nav
scrollingTop: pageTop,
useAbsolutePositioning: false
});
});
</SCRIPT> <!--10/15/2014 END -->
<?php
}
?>
It's smaller and cleaner and the file_get_contents() can get the job done. But you always need to make sure you have the html of the page.

Displaying MySQL in PHP

So far, I have this program that links my phpmyadmin database to my php script. Now, I need to display certain things in a table like "all records," "all contacts whose last name starts with S," "all pet owners," etc. My question is: is there a simpler way to insert code into my php script to display the information from my database. Right now I have that long echo statement to display the information. Is there a way I can just use something like a SELECT * statement to display all records and to simplify my code?
<?php
$db_hostname='localhost';
$db_username='root';
$db_password='';
$db_database='Address Book';
$connection = new mysqli( $db_hostname,
$db_username,
$db_password,
$db_database);
if ($connection->connect_error) {
echo "Sorry";
} else {
echo "Connected!<br><br>";
$sql = "SELECT * FROM People";
$result = $connection->query($sql);
if (!$result) die ($connection->error);
$n = $result->num_rows;
for ($i=1; $i<=$n; $i++) {
$row = $result->fetch_array(MYSQLI_ASSOC);
echo "<table>
<tr><th>ID</th><th>First Name</th><th>Last Name</th>
<th>Street Address</th><th>City</th>
<th>State</th><th>Zip Code</th>
<th>Email Address</th><th>Comment</th>
<th>Number of pets</th></tr>";
echo "<tr><td width=20>" . $row['iD'] . "</td><td>" . $row['First Name'] . "</td><td width=40>" .
$row['Last Name'] . "</td><td width=200>" . $row['Street Address'] . "</td><td width=30>" .
$row['City'] . "</td><td width=40>" . $row['State'] . "</td><td width=30>" .
$row['Zip Code'] . "</td><td width=40>" . $row['Email Address'] . "</td><td width=20>" .
$row['Comment'] . "</td><td width=10>" . $row['Number of pets'] . "</td></tr>";
}
echo "</table>";
}
?>
You should a table structure first then insert your PHP codes within the structure. E.g:
<?php
// Put your MYSQLI retrievals codes here
?>
<table>
<tr>
<th>FIELD_1</th>
<th>FIELD_2</th>
<th>FIELD_3</th>
</tr>
<?php
while ($rows = $result->fetch_array(MYSQLI_ASSOC))
{
?>
<tr>
<td><?php echo $rows['field_1']; ?></td>
<td><?php echo $rows['field_2']; ?></td>
<td><?php echo $rows['field_3']; ?></td>
</tr>
<?php
}
?>
</table>
Technically you are doing everything alright, but there are some more sophisticated ways to develop the things you want.
Take a look at the following links:Object oriented programming in PHP and templating in PHP.
Hope this works for you:
<?php
$db_hostname='localhost';
$db_username='root';
$db_password='';
$db_database='Address Book';
$connection = new mysqli($db_hostname,$db_username,$db_password,$db_database);
if ($connection->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
} else {
echo "Connected!<br><br>";
}
$last_name = "Lastname to search"; //You can post or get lastname in here.
/* create a prepared statement */
if ($sql = $connection->prepare("SELECT * FROM People WHERE `Last Name`=?")) {
/* bind parameters for markers */
$sql->bind_param("s", $last_name);
/* execute query */
$sql->execute();
/* instead of bind_result: */
$result = $sql->get_result();
/* close statement */
$sql->close();
}
?>
<table>
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Street Address</th>
<th>City</th>
<th>State</th>
<th>Zip Code</th>
<th>Email Address</th>
<th>Comment</th>
<th>Number of pets</th>
</tr>
</thead>
<tbody>
<?
/* now you can fetch the results into an array */
while ($row = $result->fetch_assoc()) {
?>
<tr>
<td width=20><?=$row['iD'];?></td>
<td><?=$row['First Name'];?></td>
<td width=40><?=$row['First Name'];?></td>
<td width=200><?=$row['Street Address'];?></td>
<td width=30><?=$row['City'];?></td>
<td width=40><?=$row['State'];?></td>
<td width=30><?=$row['Zip Code'];?></td>
<td width=40><?=$row['Email Address'];?></td>
<td width=20><?=$row['Comment'];?></td>
<td width=10><?=$row['Number of pets'];?></td>
</tr>
<?
}
?>
</tbody>
</table>

DataTable plugin not working with dynamically generated php table (arrows wouldn't show up too)

I created a table from using php and added the plugin (used demo_table.css). The arrows wouldn't show on the result page and it doesn;t apply any css.
Here is my php code:
$result = mysqli_query($link, $sql);
$num_rows = mysqli_num_rows($result);
echo '<table cellpadding = "0" cellspacing="0" border="0" id="datatables" class="display">';
echo '<thead>';
echo '<tr>';
echo '<th>SNo.</th>
<th>Username</th>
<th>Trip ID</th>
<th>Destination</th>
<th >Leave Date</th>
<th>Return Date</th>
<th>Total</th>
<th>Submit Date</th>
<th >Status</th>
<th >Reason</th>
<th >Update</th>';
echo '</tr>';
echo '</thead>';
echo '<tbody>';
} else {
echo('not valid user');
}
if (!$result) {
die(mysqli_error($link));
}
if ($num_rows<=0){
echo('not valid user');
}
elseif ($num_rows>0){
$i=1;
while($row = mysqli_fetch_assoc($result)) {
$grandtotal = $row['flight_estimate'] + $row['registration_fee'] + $row['total_cost'];
$status = $row['status'];
if(($status == 'Approved') || ($status == 'Denied')){
$newcolumn = '<td></td>';
}
else{
$newcolumn = '<td>Approve/Deny</td>';
}
echo '<tr>';
echo '<td>'. $i++ .'</td><td>'.$row['username'].'</td><td>'.$row['trip_id'].'</td><td>'.$row['destination'].'</td><td>'.date('d/m/Y',strtotime($row['leave_date'])).'</td><td >'.date('d/m/Y',strtotime($row['return_date'])).'</td><td >'. round($grandtotal,2).'</td><td >'.date('d/m/Y',strtotime($row['updateddate'])).'</td><td >'.$row['status'].'</td><td >'.$row['reason'].'</td>'.$newcolumn;
}
echo '</tr>';
echo '</tbody>';
echo '</table>';
}
?>
Is there anything that I'm missing? All it does is center all the column values. But when I click on header nothing happens.
You need to set 'bJQueryUI' to true when you init dataTable
$("#datatables").dataTable({ 'bJQueryUI' : true });
It would help if you posted your js script as that is where your problem is.

How to create a table in HTML using PHP

I have 5 pictures stored in a folder and their links stored on the database.
I want to put them in a table of three columns on each row.
<body>
<center>
<table border='1'>
<?php
$host="";
$username="";
$password="";
$db_name="fruits_db";
$tbl_name="fruits_tbl";
$connection=mysqli_connect("$host","$username","$password","$db_name");
if (mysqli_connect_errno())
{
echo "The application has failed to connect to the mysql database server: " .mysqli_connect_error();
}
$result = mysqli_query($connection, "SELECT * FROM fruits_tbl")or die("Error: " . mysqli_error($connection));
$num_rows=mysqli_num_rows($result);
$rows = $num_rows/3;
for($i=1; $i<=$rows ; $i++)
{
echo "<tr>";
for($j=1; $j<=3; $j++)
{
while($row = mysqli_fetch_array($result))
{
echo
("<td width='180px' height='200px'>"
."<div class = 'fruit_image'>"
."<img src='"
.$row['fruit_image']
."'/>"
."</div>"
."<div class = 'fruit_title'>"
.$row['fruit_name']
."</div>"
."</td>"
);
}
}
echo "</tr>";
}
mysqli_close($connection);
?>
</table>
</center>
</body>
</html>
The above code I created, contains two FOR loops. The script should count the number of rows in the table, and then divide by 3(the number of columns on each row in the HTML table).
I wonder where I'm going wrong wit this code.
With your while($row = mysqli_fetch_array($result)){} inside your 1st for loop it will run through all your rows, before the outside loop runs 2nd/3rd time.
Here is another way to do it -
$counter = 1;
// start 1st row
echo "<tr>";
while($row = mysqli_fetch_array($result)){
// if the 4th cell, end last row, and start new row
if ($counter%3==1){
echo "</tr><tr>";
}
echo
"<td width='180px' height='200px'>"
."<div class = 'fruit_image'>"
."<img src='"
.$row['fruit_image']
."'/>"
."</div>"
."<div class = 'fruit_title'>"
.$row['fruit_name']
."</div>"
."</td>";
// increase the counter
$counter++;
}
// close the last row
echo "</tr>";
You're looping through all the results in the first table cell.
Try something like this instead:
for($i=1; $i<=$rows ; $i++) {
echo "<tr>";
for($j=1; $j<=3; $j++) {
$row = mysqli_fetch_array($result);
if ($row) {
echo(
"<td width='180px' height='200px'>"
."<div class = 'fruit_image'>"
."<img src='"
.$row['fruit_image']
."'/>"
."</div>"
."<div class = 'fruit_title'>"
.$row['fruit_name']
."</div>"
."</td>"
);
}
}
echo "</tr>";
}
If you just want to format the display with a new row after every 3 records, you could use the modulus operator:
$cntr = 0;
echo '<tr>';
while($row = mysqli_fetch_array($result)) {
$cntr++;
echo '
<td width="180px" height="200px">
<div class="fruit_image">
<img src="'.$row['fruit_image'].'" />
</div>
<div class="fruit_title">'.$row['fruit_name'].'</div>
</td>';
if ($cntr % 3 == 0 && $cntr != $num_rows)
echo '</tr><tr>';
}
echo '</tr>';
Keep in mind however that all the solutions presented so far may leave you with a last row with one or two td elements. You can fill this if you desire with empty <td> </td> columns.
print "<center><table border=1>
<tr>
<td>id</td>
<td>name</td>
<td>company</td>
<td>branch</td>
<td>job title</td>
<td>contact</td>
<td>email</td>
<td>mgs</td>
</tr>";
while($row=mysql_fetch_array($query))
{
print "<tr>";
for ($i=0;$i<=(count($row)/2);$i++)
{
print "<td>$row[$i]</td>";
} print"</tr>";
}
}
else{echo " <p>No Records Found</p>";}
<?php
function studentTable($name,$grade){
echo "<tr> <td>$name</td><td>$grade</td></tr>";
}
?>
<table style="width:100%" border="solid">
<tr>
<th>Name</th>
<th>Grade</th>
</tr>
<?php studentTable("Sarah", 90) ?>

Display Data in two column in Datatable

I have managed to display data in one column table, but would like to have two column instead. Is there a way of doing it? Here's the code I currently have. Although, it works, it prints in one long column and would like to break it into two columns.
As you can tell, I'm using jQuery Datatable.
<?php
include('config.php');
mysql_connect($host, $username, $password) or die(mysql_error()) ;
mysql_select_db('people') or die(mysql_error()) ;
$data = mysql_query("SELECT * FROM names ORDER BY RAND() LIMIT 20") or die(mysql_error());
?>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script src="datatables/dt/media/js/jquery.dataTables.js">
</script>
<style type="text/css">
/* #import "datatables/dt/media/css/demo_table.css";
.result_container{
width: 553;
} */
</style>
<script>
$(document).ready(function(){
$('#the_table').dataTable();
});
</script>
</head>
<body>
<?php
echo "<table id=\"the_table\">
<thead>
<tr>
<th>Latest names</th>
</tr>
</thead>
<tbody> ";
while($info = mysql_fetch_array( $data )){
echo"<tr> <td>" . $info['name'] . "</td>
</tr>";
}
echo" </tbody> ";
echo "</table> ";
?>
</body>
</html>
Any help will be appreciated very much.
echo "<table id=\"the_table\">
<thead>
<tr>
<th>Latest names</th>
</tr>
</thead>
<tbody>
<tr>";
while($info = mysql_fetch_array( $data )){
// if remainder is zero after 2 iterations (for 2 columns) and when $c > 0, end row and start a new row:
if( ($c % 2) == 0 && $c != 0){
echo "</tr><tr>";
}
echo "<td>" . $info['name'] . "</td>";
$c++;
} // while..
// in case you need to fill a last empty cell:
if ( ( $i % 2 ) != 0 ){
// str_repeat() will be handy when you want more than 2 columns
echo str_repeat( "<td> </td>", ( 2 - ( $i % 2 ) ) );
}
echo "</tr>
</tbody>
</table>";
?>
Just add another cell in HTML?
<?php
echo "<table id=\"the_table\">
<thead>
<tr>
<th>Latest names</th>
<th>ANOTHER_FIELD</th>
</tr>
</thead>
<tbody> ";
while($info = mysql_fetch_array( $data )){
echo"<tr> <td>" . $info['name'] . "</td><td>".$info['ANOTHER_FIELD']."
</tr>";
}
echo" </tbody> ";
echo "</table> ";
?>

Categories