I have 2 text files and read their content into 2 arrays using php. Then I create a table and display it on my site. I now want to color every cell from array 2 (column 2) based on certain values.
For Example:
if a value from array2 contains "busy", it shall be formatted red, if
it contains "available", it shall be formatted green.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<form action="" method="post" class="formbody">
<div class="codetable">
<?php
$file1 = "c:/presencetool/ramfile1.txt";
$file2 = "c:/presencetool/ramfile2.txt";
$line1= file($file1, FILE_IGNORE_NEW_LINES);
$line2 = file($file2, FILE_IGNORE_NEW_LINES);
$combine = array_combine($line1, $line2);
$html = "<table align=center>";
$html .= "<tr><td width=300px></td><td></td></tr>";
$i = 1;
foreach ($combine as $file1 => $file2):
$html .= "<tr>";
$html .= "<td>".$file1."</td>";
$html .= "<td>".$file2."</td>";
$html .= "</tr>";
$i++;
endforeach;
$html .= "</table>";
echo $html;
?>
<div class="codelabel">
</div>
</div>
</form>
</body>
</html>
I tried some possible solutions but could not bring it to work.
Any ideas? If there is any Information I should provide, just ask.
edit:
content of ramfile 1&2:
ramfile1:
User#1
User#2
User#3
...
User#n
ramfile2:
Busy
Busy
Available
Busy
...
<?php
$path = $_SERVER['DOCUMENT_ROOT'].DIRECTORY_SEPARATOR.'demo'.DIRECTORY_SEPARATOR;
$file1 = $path.'ramfile1.txt';
$file2 = $path.'ramfile2.txt';
if(file_exists($file1) && file_exists($file2)) {
$line1= file($file1, FILE_IGNORE_NEW_LINES);
$line2 = file($file2, FILE_IGNORE_NEW_LINES);
$combine = array_combine($line1, $line2);
$html = '<table align="center">';
$html .= '<tr><td width="300px"></td><td></td></tr>';
$i = 1;
foreach ($combine as $key => $value):
$html .= '<tr class="'.$value.'">';
$html .= '<td>'.$key.'</td>';
$html .= '<td>'.$value.'</td>';
$html .= '</tr>';
$i++;
endforeach;
$html .= '</table>';
echo $html;
}
?>
<style>
.Busy { background-color: #f2a179;}
.Available { background-color: #00ff00;}
</style>
foreach ($combine as $file1 => $file2):
This line makes no sense at all. It will probably run but it won't do what you describe. I think you really want something like....
foreach ($file1 as $i=>$value) {
$html .= "<tr>";
$html .= "<td>".$file1[$i]."</td>";
$html .= "<td>".$file2[$i]."</td>";
$html .= "</tr>";
}
But that you are resolving data in one file from another based on the line number is a very bad choice of data structure.
if a value from array2 contains "busy", it shall be formatted red, if it contains "available", it shall be formatted green.
There are lots of ways to do this. You could call a function....
$bgcolor=lookup_css_class($file2[$i]);
$html .= "<td class='$bgcolor'>$file2[$i]</td>";
Or you could use dependancy injection, or you could use an array lookup. Alternatively you could simply declare CSS classes based on the value and inject the value as the class name for the TD (but bear in mind this allows someone with control over the data to inject html/javascript into your page:
td.busy {background-color: red;}
td.free {background-color: green;}
...
$html .= "<td class='$file2[$i]'>$file2[$i]</td>";
Related
I have a page listing articles from a database. When user clicks a tag label they are taken to a blogsbycategory.php page. This page gets the tag parameter from the url and returns all blogs that have this tag. On the right hand side of this page I have a list of tags. How do I change the GET so when a user click a tag in the list, the url parameter will update and they can view all blogs for that chosen tag.
http://example.com/articles/blogsbycategory.php?tag=People%20management
<?php
$tag = $_GET["tag"];
$sql = "select * from blogs where tag = '$tag' " ;
$rs = mysqli_query($connect, $sql);
//get row
$fetchRow = mysqli_fetch_assoc($rs);
?>
<h3>Tags</h3>
<?php
while($row = mysqli_fetch_array($result))
{
echo '<ul style="list-style: none;">';
echo '<li>' .$row["tagName"]. '</li><hr />';
echo '</ul>';
}
?>
Something like this:
<h3>Tags</h3>
<?php
while($row = mysqli_fetch_array($result))
{
echo '<ul style="list-style: none;">';
echo '<li>' . $row["tagName"] . '</li><hr />';
echo '</ul>';
}
?>
With jQuery something like this:
<h3>Tags</h3>
<?php
while($row = mysqli_fetch_array($result))
{
echo '<ul style="list-style: none;">';
echo '<li onclick="$('#articleContainer').load(' . $row["tagName"] . ')">' . $row["tagName"] . '</li><hr />';
echo '</ul>';
}
?>
<div id="art" style="width: 600px; height: 800px; border: 1px solid grey;"></div>
List them as links
<h3>Tags</h3>
<ul>
<?php while($row = mysqli_fetch_array($result)) { ?>
<li><?php echo htmlspecialchars($row["tagName"]); ?></li>
<?php } ?>
</ul>
And please quote the data before you use them in a SQL statement.
I have a little problem to hide and show table. I tred this, I haven't error in console but it does'nt work. Maybe I forget something wrong or make a mistake.
I saw the data inside the code but it does'nt appear when I click on the link.
Thank you
$i = 0;
foreach($option_attributes_name as $value) {
$content .= ' <li class="col-md-12"><a onclick="showTabOption' . $i .'" class="nav-link" data-toggle="tooltip" data-target="#section_ProductsAttributesNewApp_content" href="' . OSCOM::link('index.php?A&Catalog\Products&Edit&cPath=' . $_GET['cPath'] . '&pID=' . $_GET['pID'] . '#tab-option' . $i) . '"><i class="fa fa-minus-circle"></i> ' . $value['name'] . '</a></li>';
// $i++;
$t++;
}
$Qoption = $this->app->db->prepare('select option_id, type
from :table_test_products_options_attributes');
$Qoption->execute();
$i =0;
while ($Qoption->fetch()) {
$content .= '<div id="tab-option' . $i . '" style="display:none;">';
$content .= '<h4>' . $Qoption->value('type') . '</h4>';
$content .= '<table width="100%" cellpadding="5" cellspacing="0" border="0">
</table>
</div>
';
$content .= '
<script type="text/javascript"><!--
function showTabOption' . $i . '() {
$("a[href=\'#tab-option' .$i . '\']").parent().remove();
$(\'#tab-option'. $i . '\').remove();
$(\'#option a:first\').div(\'show\');
}
//--></script>
';
$i++;
}
You can settle a few issues first by adjusting how you are doing things with the js and jquery use.
1) Setting up the elements you will click with just a class, and data-tableid:
$content .= '<li class="col-md-12"><a class="showTabOption nav-link" data-tableid="'. $i .'" ... etc etc ...</a>';
^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^
2) Fix this in your first loop: Change $t++; to $i++;.
3) You do not need to adjust the table builds (the ones from the while loop):
$content .= '<div id="tab-option'. $i .'" style="display:none;">';// this is ok
4) Then adjust your SINGLE javascript function. Have it output OUTSIDE of the while loop (since this must only be done once):
<script language="Javascript" type="text/javascript">
$( document ).ready(function() {
$(".showTabOption").click(function(e) {
e.preventDefault(); // stop the a href from firing off
var tableid = $(this).data('tableid'); // the table in question
$(this).parent().remove(); // remove what you clicked?
$("#tab-option"+ tableid ).show(); // show your options table
});
});
</script>
This should get you rolling on making that table (the div surrounding it) show up when you click one of those links. Of course it looks like you have much more going on in there, table rows, something with the href link value, and the sort, but you only asked about showing the table div.
TL;DR: Full example of your example code adjusted:
<?php
$i = 0;
foreach($option_attributes_name as $value) {
$content .= '<li class="col-md-12"><a class="showTabOption nav-link" data-tableid="'. $i .'" data-toggle="tooltip" data-target="#section_ProductsAttributesNewApp_content" href="'. OSCOM::link('index.php?A&Catalog\Products&Edit&cPath='. $_GET['cPath'] .'&pID='. $_GET['pID'] .'#tab-option'. $i) .'"><i class="fa fa-minus-circle"></i> '. $value['name'] .'</a></li>';
$i++;
}
$Qoption = $this->app->db->prepare('select option_id, type
from :table_test_products_options_attributes');
$Qoption->execute();
$i = 0;
while ($Qoption->fetch()) {
$content .= '<div id="tab-option'. $i .'" style="display:none;">';
$content .= '<h4>'. $Qoption->value('type') .'</h4>';
$content .= '<table width="100%" cellpadding="5" cellspacing="0" border="0">';
// table tr rows go here
$content .= '</table>';
$content .= '</div>';
$i++;
}
?>
<script language="Javascript" type="text/javascript">
$( document ).ready(function() {
$(".showTabOption").click(function(e) {
e.preventDefault(); // stop the a href from firing off
var tableid = $(this).data('tableid'); // the table in question
$(this).parent().remove(); // remove what you clicked?
$("#tab-option"+ tableid ).show(); // show your options table
});
});
</script>
Question:
I have a div element with id of "tableholder" which is purely to hold the output on a javascript function that pulls data via ajax from a PHP file.
Within the tableholder element, is a list.js table that works if we simply include he php file instead of calling it via ajax and setting it via innerHTML = "".
How do I use the contents of innerHTML of the tableholder div when it has been created dynamically?
Code so far:
PHP File called:
<?php
// Connection details for the database being called.
include 'connection.php';
// Putting the query to the database in a variable called "$assets".
$assets = "SELECT * FROM assetregister.getassets";
$assetPull = $conn->query($assets);
$output = "";
// Pulling all of the details from the database and displaying them on the page within the inidividual divs.
if ($assetPull->num_rows > 0) {
$output .= "<div id='users'>";
$output .= "<input class='search form-control mt-2' placeholder='Search...' />";
$output .= "<div class='m-2'>";
$output .= "<button class='sort btn' data-sort='model'>Sort By Model</button>";
$output .= "<button class='sort btn ml-2' data-sort='domain'>Sort By Domain</button>";
$output .= "<button class='sort btn ml-2' data-sort='location'>Sort By Location</button>";
$output .= "</div>";
$output .= "<table class='table table.hover list'>";
$output .= "<thead>";
$output .= "<th style='text-align: center;'>Model</th>";
$output .= "<th style='text-align: center;'>Serial Number</th>";
$output .= "<th style='text-align: center;'>Asset Number</th>";
$output .= "<th style='text-align: center;'>Domain</th>";
$output .= "<th style='text-align: center;'>Location</th>";
$output .= "<th style='text-align: center;'>Type</th>";
$output .= "</thead>";
while ($row = $assetPull->fetch_assoc()) {
$output .= "<tbody class='list' style='text-align: center;'>";
$output .= "<td class='model'>" . $row['modelName'] . "</td>";
$output .= "<td class='serialNumber'>" . $row['serialNumber'] . "</td>";
$output .= "<td class='assetNumber'>" . $row['assetNumber'] . "</td>";
$output .= "<td class='domain'>" . $row['domain'] . "</td>";
$output .= "<td class='location'>" . $row['locationName'] . "</td>";
$output .= "<td class='type'>" . $row['type'] . "</td>";
}
$output .= "</tbody>";
$output .= "</table>";
$output .= "</div>";
// If there is no rows in the table that is being called then they will display 0 Results... See below.
} else {
$output .= "0 results";
}
echo $output;
$conn->close();
?>
This works:
<div class="container-fluid">
<div class="container">
<div class="row">
<main class="col-12" style="margin-top: 80px;">
<button class="btn btn-primary" onclick="assetSubmit()" style="width: 100%;">Add An Asset</button>
<?php include 'scripts/getAsset.php'; ?>
</main>
</div>
</div>
</div>
<script>
populatetable('tableholder');
window.onload = function () {
var options = {
valueNames: ['model', 'serialNumber', 'assetNumber', 'domain', 'location', 'type']
};
var userList = new List('users', options);
};
</script>
This outputs the table and all of the list.js functions work fine as expected.
This Doesn't Work:
<div class="container-fluid">
<div class="container">
<div class="row">
<main class="col-12" style="margin-top: 80px;">
<button class="btn btn-primary" onclick="assetSubmit()" style="width: 100%;">Add An Asset</button>
<!-- Pulling in the results of the assets (most recent assets) -->
<div id="tableholder"></div>
<!-- end -->
</main>
</div>
</div>
</div>
<!-- PHP include for the footer -->
<?php include 'assets/layout/footer.php'; ?>
<!-- end -->
<script>
populatetable('tableholder');
window.onload = function (){
var options = {
valueNames: [ 'model', 'serialNumber', 'assetNumber', 'domain', 'location', 'type']
};
var userList = new List('users', options);
};
function populatetable(name){
$.ajax({
url: "scripts/getAssets.php",
success: function(data){
document.getElementById(name).innerHTML = data;
}
})
}
</script>
What I can assume:
From the various console.log lines and php echos I have put in to test the code, it would appear that the issue it that the javascript command for initiating the list.js table isn't able to find the "user" table that is created by the document.getElementById(name).innerHTML = data; in the populatetable() function. I know this because the folllowing shows blank:
console.log(document.getElementById(tableholder).innerHTML);
What am I doing wrong, or is it not possible to pull the innerHTML data of a dynamically created element?
The problem is that by the time you're calling List(), the ajax call hasn't finished yet, since it's asynchronous.
Try this instead:
var options = {
valueNames: ['model', 'serialNumber', 'assetNumber', 'domain', 'location', 'type']
};
var userList;
$(document).ready(function() {
populatetable('#tableholder');
});
function populatetable(id) {
$.ajax({
url: "scripts/getAssets.php",
success: function(data) {
$(id).html(data);
userList = new List('users', options);
}
});
}
Here I'm using jQuery everywhere it's useful, and I'm calling List() only after the data is actually inserted.
Also note, that like I mentioned in my comment, you need to move the <tbody> line outside the loop.
I haven't worked much with php and javascript and was hoping to get some help. I want to be able to detect which button was clicked exactly. I'm creating one button per row but I don't know how to figure out what row the click was made in. This is what I have so far...
# Get all the table data from the database
$getData = mysqli_query($conn, "SELECT * FROM `query_table`") or die ("Error occured while selecting!");
// echo '<form method="post" action="index.php">';
echo '<table border="1">';
echo '<tr>';
echo '<td>Questions</td>';
echo '<td>Likes</td>';
echo '<td></td>';
echo '</tr>';
# Loop through each row and print out the question
while ($row = mysqli_fetch_array($getData)) {
echo '<tr>';
echo '<td>';
echo $row['Question'];
echo '</td>';
echo '<td>';
echo $row['Likes'];
echo '</td>';
echo '<td>';
?>
<input type="button" id="myButton" value="Like" onclick="myFunc(<?=$row['ID']?>)" />
<?php
echo '</td>';
echo '</tr>';
}
echo '</table>';
// echo '</form>';
echo '<p id="text"></p>';
mysqli_close($conn);
?>
<script type="text/javascript">
function myFunc(id) {
document.getElementById("text").innerHTML = id;
}
</script>
So far this prints out the row id where the button was clicked, but I don't suppose I can assign that parameter value directly to a php variable that I can then use for mysql queries. How is stuff like this normally done, please help.
<input type="button" data-id="<?=$row['ID']?>" value="Like" onclick="myFunc(this)">
and
<script type="text/javascript">
function myFunc(button) {
document.getElementById("text").innerHTML = button.getAttribute('data-id');
}
</script>
In JavaScript the token "this" refers to the context in which the code is running which in this case is the button. Store custom data in attributes prefixed with data- to ensure they are not disturbed - standard practise.
I am trying to update a column on my database. The user will click the confirm button and an email is sent to the user confirming a list of jobs and at the same time change the field status in column "confirmed" to "Yes".
I am able to send an email to the user but i have no clue as to why the column id like to update in my database doesn't work.
Here is my code
php:
<?php
ini_set("display_errors",1);
error_reporting(-1);
require("../controllers/cn.php");
include("/usr/share/php/Mail.php");
include("/usr/share/php/Mail/mime.php");
// Get the purchase order details
$query = mysql_query("SELECT Jobs.* FROM Jobs where job_status = 'Dispatched'") or die(mysql_error());
// Set the email content
$text = 'Text version of email';
$html .= '<html><body>';
$html .= '<p style="font-family: Arial, Helvetica, sans-serif; font-size: 22px; font-weight: bold; text-transform: uppercase; text-align: center;">Spineless Dispatch Summary</p>';
$html .= '<p style="font-family: Arial, Helvetica, sans-serif; font-size: 13px; text-align: center;">Please find below a summary of all dispatched orders: </p>';
$html .= '<table border="1" cellspacing="0" cellpadding="0" align="center"><tr><th width="200">Order Ref.</th><th width="200">First Name</th><th width="200">Last Name</th><th width="200">Tracking No.</th></tr>';
while($row = mysql_fetch_array($query)) {
$html .= '<tr>';
$html .= '<td style="padding: 10px;">'.$row['order_ref'].'</td>';
$html .= '<td style="padding: 10px;">'. $row['first_name'].'</td>';
$html .= '<td style="padding: 10px;">'.$row['last_name'].'</td>';
$html .= '<td style="padding: 10px;">'.$row['tracking_number'].'</td>';
$html .= '</tr>';
}
$html .= '</table></body></html>';
//$file = "/mnt/Jobs/Purchase_Orders/".date("Y", strtotime($row['created']))."/".date("F", strtotime($row['created']))."/PO".$row['id'].".pdf";
$crlf = "\n";
// Set customers email
$sendAddress = "rachelle#variouk.com";
// Set the from address
$hdrs = array(
'From' => 'rachelle#variouk.com',
'Subject' => 'Spineless System'
);
// Create the email
$mime = new Mail_mime(array('eol' => $crlf));
$mime->setTXTBody($text);
$mime->setHTMLBody($html);
//$mime->addAttachment($file, 'application/pdf');
$body = $mime->get();
$hdrs = $mime->headers($hdrs);
// Send the email
$mail =& Mail::factory('mail');
// Paper company address
$mail->send($sendAddress, $hdrs, $body);
// Production email address (production#variouk.com)
$mail->send("rachelle#variouk.com", $hdrs, $body);
// Update the sent status of the order
$result = mysql_query("UPDATE Jobs SET confirmed = 'Yes' WHERE order_ref = '".$order_ref."' ");
header("location: joblist.php");
?>
HTML:
<div id="buttons" align="center">
<p style="padding-bottom: 15px; font-weight: bold; font-size: 14px;">Please confirm these jobs</p>
<button type="submit" class="btn btn-primary" onclick="javascript:window.location='email.php">Confirm</button>
<button class="btn btn-default btn-wide" onclick="javascript:window.location="'joblist.php'";>Cancel</button>
</div>
Edit2:
$order_refs = array();//array of orders to update in db.
while($row = mysql_fetch_array($query)) {
$html .= '<tr>';
$html .= '<td style="padding: 10px;">'.$row['order_ref'].'</td>';
$html .= '<td style="padding: 10px;">'. $row['first_name'].'</td>';
$html .= '<td style="padding: 10px;">'.$row['last_name'].'</td>';
$html .= '<td style="padding: 10px;">'.$row['tracking_number'].'</td>';
$html .= '</tr>';
$order_refs[]=$row['order_ref'];
}
And to update using ref from array
$result = mysql_query("UPDATE Jobs SET confirmed = 'Yes' WHERE order_ref IN ('". implode("', '", $order_refs) ."') ");
Let me know if it works.
Original:
Try adding
if(!$result){
echo mysql_error();
}
after
$result = mysql_query("UPDATE Jobs SET confirmed = 'Yes' WHERE order_ref = '".$order_ref."' ");
And tell me what does it say. I'll update my answer with a fix for that error. (I cannot comment on Questions yet, still low reputation)
Edit: as #Santik noted $order_ref is not defined in this code, so the fix would be to use $row['order_ref']
$result = mysql_query("UPDATE Jobs SET confirmed = 'Yes' WHERE order_ref = '".$row['order_ref']."' ");