SQL server table to HTML table with pivoting - javascript

I am trying to make a SQL server table display pivoted in HTML using PHP.
The columns of the HTML table would be the content of the "CONCEPT" column of the SQL table and the content of the HTML columns would be the result of the "DATA" column of the SQL.
Not all records have the same number of "columns" that is, for example the serial number 12345 has the RAM column but the serial number 67890 does not, so the HTML table cell should appear as blank.
This is the tab delimited file: https://pastebin.com/sFJEHJLm
All the concepts of each article have a record with the same value as "LINE", but I don't know how to take advantage of this data to make the painting of the table.
I have tried to load each of the SQL columns in different PHP arrays and then cycle through the array by painting the HTML table but, at the moment a serial number that has a column arrives, the relationship of the results in the HTML table is lost With the correct column.
if ($_REQUEST['accion'] == "abrir_auditoria") {
$array_titulos = array();
$Total = 0;
$Actual = 0;
try
{
$sql = "SELECT * FROM AUDITORIAS_LIN WHERE AUDITORIA = '" . $_REQUEST['id'] . "'";
$q = $pdo->query($sql);
$q->setFetchMode(PDO::FETCH_ASSOC);
while ($r = $q->fetch()):
if (!in_array(htmlspecialchars($r['CONCEPTO']), $array_titulos))
{
array_push($array_titulos, htmlspecialchars($r['CONCEPTO']));
}
endwhile;
echo "<table border=1>";
echo "<tr>";
foreach ($array_titulos as $titulo)
{
echo "<th>$titulo</th>";
}
echo "</tr>";
echo "<tr>";
$q = $pdo->query($sql);
$q->setFetchMode(PDO::FETCH_ASSOC);
$Total = key(array_slice($array_titulos, -1, 1, true));
while ($r = $q->fetch()):
if ($Total != $Actual)
{
echo "<td>" . htmlspecialchars($r['DATO']) . "</td>";
$Actual++;
} else {
echo "</tr><tr>";
echo "<td>" . htmlspecialchars($r['DATO']) . "</td>";
$Actual = 0;
}
endwhile;
echo "</tr>";
echo "</table>";
}
catch(PDOException $pe)
{
die("database connect error:". $pe->getMessage());
}
}

Related

javascript document.getElementById only reading first value from php mysql database

Let me try and say this in a way that doesnt get anyone angry or confused.
I have a value that I am outputting into a table.
The value is populated by mysql and php.
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<table>";
echo "<tr>";
echo "<td id='countryDbId'>".$row['country']."</td>";
echo "</tr>";
echo "</table>";
}
$conn->close();
}
?>
Then I try to read all the values that were output with javascript.
<script>
var country = document.getElementById("pp").innerHTML;
console.log(country);
</script>
The output is only the first value even though there are over 100 values in that column.
Any help would be appreciated.

PHP and HTML table search using javascript

I want to create a search box, that only displays matched entries as search phrases are typed; the same in function as described here:
How to perform a real time search and filter on a HTML table
The difference is, the table I have is created from a PHP loop - and SQL data. But, I am unsure how to adopt the code to work for me.
Personally, I think it could be related to the "// printing table rows" section.
Here is the code:
var $search_rows = $('#table tr');
$('#search').keyup(function() {
var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();
$search_rows.show().filter(function() {
var text = $(this).text().replace(/\s+/g, ' ').toLowerCase();
return !~text.indexOf(val);
}).hide();
});
<html>
<script src="./jquery-1.6.4.js"></script>
<script src="./sorttable.js"></script>
<script src="./searchbox.js"></script>
<link rel="stylesheet" href="styles.css">
<head>
<title>Tau Empire Cadre Census</title>
</head>
<body>
<?php
//// //// //// ////
// DATABASE
//// //// //// ////
//database credentials
$db_host="localhost";
$db_user="tau";
$db_pwd="kuhohNg3";
$db="tau_census";
$db_table="cadres";
//make the connection
if (!mysql_connect($db_host, $db_user, $db_pwd))
die("Can't connect to database");
if (!mysql_select_db($db))
die("Can't select database");
// sending query
$result = mysql_query("SELECT * FROM {$db_table}");
if (!$result) {
die("Query to show fields from table failed");
}
//assign a variable the number of returned table fields
$fields_num = mysql_num_fields($result);
//// //// //// ////
// HEADING
//// //// //// ////
echo "<h1>Tau Empire Cadre Census</h1>";
// Search box
echo '<input type="text" id="search" placeholder="Type to search">';
//// //// //// ////
// TABLE
//// //// //// ////
//create the table, and use the JS sortable script
echo '<table id="table" class="sortable"><tr>';
// printing table headers
echo "<td class=headings>Designation</td>";
echo "<td class=headings>Location</td>";
echo "<td class=headings>Founding</td>";
echo "<td class=headings>Commanding Officer</td>";
echo "<td class=headings>Current Status</td>";
echo "<td class=headings>Current Location</td>";
echo "<td class=headings>Mission</td>";
echo "</tr>\n";
// printing table rows
while($row = mysql_fetch_row($result))
{
echo "<tr>";
// For each field print the content
for($i=1; $i<$fields_num; $i++) {
echo "<td>" . $row[$i] . "</td>";
}
echo "</tr>";
}
echo "</table>";
mysql_free_result($result);
?>
</body>
</html>
Running this does not throw up any errors, but nor does it work either. This requires brains greater than mine to work out, please.
I have this working now, thanks for all the assistance. It was a possible combination of the following:
i) Having the following script lines inserted correctly:
<script src="./jquery.min.js"></script>
<script src="./jquery-1.6.4.js"></script>
ii) Wrapping the external JS in $(function(){...});
iii) Incorrectly constructing my table rows and data fields.
Since you think the problem lies in the "printing table rows" section, I will point out that indeed you have formatting issues in that section, fix them like this and it might solve some of the problems:
// printing table rows
while($row = mysql_fetch_row($result))
{
echo "<tr>";
// For each field print the content
for($i=1; $i<$fields_num; $i++) {
echo "<td>" . $row[$i] . "</td>";
}
echo "</tr>";
}

Click a <td> element to cause a self posting event with an SQL query involving multiple tables. PHP

What I have is a table that is pulled from a database. The goal is that I want to be able to click on any team and have a self posted page produce a table with previous yearly results per row (multiple tables, year by year) and a row of total stats. For example: Click on San Jose and get 2014-2015 stats in 1 row, 2015-2016 in the next row and then a total of all the seasons added up. Not really sure how to implement it. I would love to get some suggestions on the best way to attack this problem.
Link To My Project
Here is some of my code, so you can see how I am doing it so far.
$query = "SELECT * FROM standings2015_2016 WHERE confid='2' ORDER BY pts DESC, losses ASC, otl ASC, gf-ga DESC";
$result = $db->query($query);
echo "<h3>Western Conference</h3>";
echo "<table class='table sortable'>";
echo "<tr class='TableHeaders'>";
echo "<td class='hover'>Place</td>";
echo "<td class='hover'>Team</td>";
echo "<td class='hover'>Wins</td>";
echo "<td class='hover'>Losses</td>";
echo "<td class='hover'>OTL</td>";
echo "<td class='hover'>Points</td>";
echo "<td class='hover'>GF</td>";
echo "<td class='hover'>GA</td>";
echo "<td class='hover'>+ / -</td>";
echo "</tr>";
$i = 0;
foreach ($result as $row) {
$i++;
$plusMinus = ($row['gf'] - $row['ga']);
echo "<tr>";
echo "<td>";
echo $i;
echo "</td><td class='hover2'>";
echo stripslashes($row['name']);
echo "</td><td>";
echo stripslashes($row['wins']);
echo "</td><td>";
echo stripslashes($row['losses']);
echo "</td><td>";
echo stripslashes($row['otl']);
echo "</td><td>";
echo stripslashes($row['pts']);
echo "</td><td>";
echo stripslashes($row['gf']);
echo "</td><td>";
echo stripslashes($row['ga']);
echo "</td><td>";
echo $plusMinus;
echo "</td>";
echo "</tr>";
}
echo "</table>";
So echo stripslashes($row['name']); is the team name I want to click on. Can this be done with an onclick event to prompt a query and a self post?
In order to do what you want, we can use jQuery and Ajax.
First is to download jQuery here.
Then create a link element for each team name that has class and data-artid tag:
echo ''.stripslashes($row['name']).'';
Then create the script:
<script src="jquery-1.9.1.min.js"></script> <!-- REPLACE NECESSARY JQUERY FILE DEPENDING ON THE VERSION YOU HAVE DOWNLOADED -->
<script type="text/javascript">
$(document).ready(function(){ /* PREPARE THE SCRIPT */
$(".teamname").click(function(){ /* WHEN A TEAM IS CLICKED */
var elem = $(this); /* STORE THE CLICKED TEAM */
var teamid = elem.attr("data-artid"); /* GET THE ID OF THE CLICKED TEAM NAME */
$.ajax({ /* PREPARE THE AJAX */
type: "POST", /* METHOD TO BE USED TO PROCESS THE PASSED DATA */
url: "action.php", /* THE PAGE WHERE THE DATA WILL BE PROCESSED */
data: {"teamid": teamid}, /* THE DATA WE WILL PASS */
success: function(result){
$("#content").html(result); /* WE WILL SHOW THE RETURNED DATA TO YOUR CONTENT DIV */
} /* END OF SUCCESS */
}); /* END OF AJAX */
});
});
</script>
And for your action.php, which will process the passed on data using Ajax:
<?php
/* INCLUDE YOUR DB CONNECTION HERE */
if(!empty($_POST["teamid"])){
$tr = '
<table class="table sortable">
<tr class="TableHeaders">
<td class="hover">Team</td>
<td class="hover">Wins</td>
<td class="hover">Losses</td>
<td class="hover">OTL</td>
<td class="hover">Points</td>
<td class="hover">GF</td>
<td class="hover">GA</td>
</tr>
';
$result = $db->query("SELECT name, wins, losses, otl, pts, gf, ga FROM standings2014_2015 WHERE teamid = '".$_POST["teamid"]."'");
foreach ($result as $row) {
$tr .= '
<tr>
<td>'.$row["name"].'</td>
<td>'.$row["wins"].'</td>
<td>'.$row["losses"].'</td>
<td>'.$row["otl"].'</td>
<td>'.$row["pts"].'</td>
<td>'.$row["gf"].'</td>
<td>'.$row["ga"].'</td>
</tr>
';
} /* END OF LOOP */
$tr .= '</table>';
echo $tr; /* RETURN THIS TO AJAX */
} /* END OF NOT EMPTY teamid */
?>
You can assign an ID to each one of the teams in your database and then use that ID to pull the information in one php file. In that file you can just get the ID perform the query search and display the information in a different page.
In the index.php where you display all the teams you can add a link to the team.php.
echo "<a href=\"team.php?Id=".$team['Id']."\">";
team.php
if (isset($_GET['Id']) && is_numeric($_GET['Id']))
{
// Perform database query
$teamID = mysql_escape_string($_GET['Id']);
// Assign the query to a variable
$query = "SELECT name, wins, losses, otl, pts, gf, ga FROM standings2014_2015 WHERE Id=".$teamID.";";
$result = $conn->query($query);
// If the user exists
if ($result)
{
while ($team = $result->fetch_assoc())
{
echo $team["name"];
echo $team["wins"];
....
// Display the information in the table
}
}
I suggest this code:
For standings.php modify this:
echo stripslashes($row['name']);
by:
echo "<a href=\"standings.php?name=".stripslashes($row['name'])."\">";
Then standings.php should view like this:
if (isset($_GET['name']) && !is_empty($_GET['name']))
{
$kname = mysql_escape_string($_GET['name']);
$query = "SELECT name, wins, losses, otl, pts, gf, ga FROM standings2014_2015 WHERE name=".$kname.";";
$result = $db->query($query);
if ($result)
{ echo "<table class='table sortable'>";
foreach ($result as $row)
{
$tr .= '
<tr>
<td>'.$name.'</td>
<td>'.$wins.'</td>
<td>'.$losses.'</td>
<td>'.$otl.'</td>
<td>'.$pts.'</td>
<td>'.$gf.'</td>
<td>'.$ga.'</td>
</tr>
';
echo $tr;
}
echo "</table>";
}
}else{
//YOUR ACTUAL CODE
}

Creating a html table with javascript by entering mysql values

The question might not really be clear because I could not think of something that could suit my problem, anyway, I am importing some mysql values using php and creating a html table using javascript, however I am having problems with the PHP as well as Javascript part, Also if anyone could tell me how I could just import values from MYSQL database and make a html table with it (That's basically what I am trying to do)
1.) PHP is not importing values from MYSQL correctly
2.) On console it says: "Uncaught SyntaxError: Unexpected token ILLEGAL"
The following is my code,
<?php
$con = mysqli_connect("localhost","root","","human_information");
$result = mysqli_query($con,"SELECT * FROM basic_human_info");
$rows = mysqli_num_rows($result);
$columns = mysqli_num_fields($result);
?>
<body>
<script type="text/javascript">
function createTable(){
var tBody = document.getElementsByTagName("body")[0];
var table = document.createElement("table");
table.style.border=1;
table.style.width='50%';
table.setAttribute('border',1);
var rows = "<?php echo $rows; ?>";
var columns = "<?php echo $columns ?>";
for(var i=0;i<columns;i++){
var tr = document.createElement("tr");
for(var j=0;j<rows;j++){
var td = document.createElement("td");
td.appendChild(document.createTextNode("
<?php
$sql = mysqli_query($con,"SELECT 'First Name' FROM basic_human_info");
echo mysqli_fetch_assoc($sql);
?>
"));
tr.appendChild(td);
}
table.appendChild(tr);
}
tBody.appendChild(table);
}
createTable();
</script>
</body>
You are outputting an array with echo (echo mysqli_fetch_assoc($sql);) which will just print Array in the middle of the Javascript. That leads to the Uncaught SyntaxError.
But the question rather is: Why use Javascript? Try it with HTML first until you get the PHP right, then do what ever you are planning to do with Javascript.
Like this you can try in php directly
while ($row = mysqli_fetch_array($stmt)) {
echo "<tr>";
echo "<td>" . $row["aid"] . "</td>";
echo "<td>" . $row["aname"] . "</td>";
echo "</tr>";
}

Display data in tabular manner in PHP form

I want to do something like this..
I have a update form in PHP, which contains around 15 fields,
I want to show some data in tabular manner while you open the page for update..
Senario:
If you want to update a record of a person on day to day basis, I have the feature with me to search out that person form database, and when you click on update data..
it should show in a manner that,
field1.....----------
field2.....----------
field3.....----------
and now,
for field4,5,6,7
if these fields contain the data then show in a table manner with fields 4,5,6,7 as coloums and no of rows depending upon the number of entries (should be non editable)(assume the case of multiple input)
then form will continue.
field4.....--------
field5.....--------
field6.....--------
field7.....--------
typically these field(4,5,6,7) gets their value update frequently and I have to maintain the previous inputs also.
help me out with some solution, as I am unable to figure out how to do this?
before that i was using this.. here i was having a form field which can generate 5 options, and will populate the fields with data if u have entered before, now i want to change the display as I don't want user to play with the old data, so I want to show old data into a table and enter new data via a simple text field,
as their is no point to keep these multiple input form field as user is updating only one value at a time.
<script>
function Submitted_Date(value,object)
{
value = document.getElementById("subdate_num").value;
if (value > -1) {
var input= new Array(value);
var p;
//alert("Enter The fields You Know ");
var ele = document.getElementById("subdate");
if(ele.hasChildNodes())
{
var len = ele.childNodes.length;
while(ele.childNodes.length - value > 1)
{
ele.removeChild(ele.lastChild);
}
}
for (var i=len-1;i<value;i++)
{
p= i+1;
input[i] = document.createElement('div');
input[i].innerHTML = 'Submitted_Date' + p + ': <input type="text" value="" name="subdate' + p + '" id="subdate' + p +'" size = 25 onclick="javascript: showCalendar("Submitted_Date'+ p +'")"/>';
document.getElementById("subdate").appendChild(input[i]);
var subdate = 'subdate' + p;
}
}
document.getElementById("subdate1").focus();
}
</script>
<tr>
<td> Submitted Date :
<select name="subdate_num" id="subdate_num" onChange="return Submitted_Date(this.value,this.form)">
<?php
for ($i=0;$i<=5;$i++)
{
if ($i==0) { $temp = "<option value=$i> - </option>"; echo $temp; }
else { $temp = "<option value=$i>$i</option>";
echo $temp; }
}
?>
</select></td>
</tr>
</table>
<table>
I think this is what you want, this will show the information in a table with as many (or few) columns as you want
$query = "SELECT * FROM announcements ORDER BY announceid";
$result = mysql_query($query);
echo "<table border='1'>
<tr>
<th>Announcement ID</th>
<th>Announcement Name</th>
<th>Announcement Category</th>
<th>Approved?</th>
<th></th>
</tr>";
if ($result && mysql_num_rows($result) > 0) {
$x = 0;
while ($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['announceid'] . "</td>";
echo "<td>" . $row['title'] . "</td>";
echo "<td>" . $row['category_name'] . "</td>";
echo "<td>" . $row['status'] . "</td>";
echo '<td>Edit</td>';
echo "</tr>";
$x ++;
};
echo "</table>";
Let me know if that is what you are looking for, or if there is any other way I can help. Thanks!

Categories

Resources