Compare a current user against a list of employees logged into computers Perl, CGI - html

Not sure I am doing this correctly as it doesn't appear to be working.
Is this the correct way to declare my users, and is the If statement correctly formated?
At the top I have declared:
my $las = 'jpietrza hpietrza oszones';
These are employees we are checking against current users.
Further down in the code, I want to change the text color that is printed if the user is in the list vs. someone else.
while ( $sth->fetch() ) {
next unless defined $currentuser;
$lastlogin =~ s/ .*$//;
$host_name =~ s/1408//;
foreach ( #las ) {
if ( $currentuser eq "$_" ) {
$lacolor = "black";
last;
}
else {
$lacolor = "red";
}
}
print "<tr>";
print "<td>$host_name</td>";
print "<td><font color=\"$lacolor\">System In-Use (User Undisclosed)</font></td><td> </td>";
}

maybe there was nothing wrong with the if statement, but the whole 9 lines of code can be condensed to 1 very readable line:
$lacolor = any { /^$currentuser$/ } #las ? "black" : "red";
please
use List::Util qw/any/;
while($sth->fetch()) {
# $currentuser is assigned between the 'while' and this 'next' statement ?
# if not, then outside the loop and do not loop at all unless defined
next unless defined $currentuser;
$lastlogin=~s/ .*$//;
$host_name=~s/1408//;
$lacolor = any { /^$currentuser$/ } #las ? "black" : "red";
print "<tr>";
print "<td>$host_name</td>";
print "<td><font color=\"$lacolor\">System In-Use (User Undisclosed)</font></td><td> </td>";
}
please, also use strict; and use warnings;

I figured out how to put the array together correctly:
my #las = qw(
jpietrza
hpietrza
oszones
);
instead of:
my $las='
jpietrza
hpietrza
oszones
';

Firstly, as I think you have worked out now, the scalar variable $las and the array #las are completely different. As you've seen, you should declare and initialise your array like this:
my #las = qw(
jpietrza
hpietrza
oszones
);
Actually, I suspect this all gets easier if you store this in a hash, not an array;
my %las = map { $_ => 1 } qw(jpietrza hpietrza oszones);
Then your check just becomes:
my $lacolour = $las{$currentuser} ? 'black' : 'red';
A few more points:
Please add use strict and use warnings. And understand and fix the problems they reveal.
The quotes are unnecessary in if ($currentuser eq "$_").
Using a templating system to create the output will make your life a lot easier.
Update: Oh, and one I forgot earlier. It's 2017. No-one has used the font element in HTML for fifteen years. Take a look at CSS.

Related

powershell passing by reference

I'm trying to pass a JSON by reference and then add something to it. For example, I want to get the same thing as:
$json.commontokens.search.tokens.token += $newItem
I keep the keys following $json in a list of strings in $jsonList (since the keys are unknown and can change) to build $json.commontokens.search.tokens.token:
$jPath = $json
foreach($item in $jsonList){
$jPath = $jPath.$item
}
As a result, $jpath += $newItem doesn't keep the change made to $json (but works for $jpath). So I thought I needed to pass by reference to keep the change. Something like
function adder{
param(
[ref]$j
$stringList
)
if ($stringList -ne $null) {
$first = $stringList.first.value
$stringList.removefirst()
adder ([ref]$j.value.$first) $stringList
} else {
return $j
}
}
$jpath = adder ([ref]$json) $jsonList
$jpath.value += $newItem
Again, this works for $jpath, but nothing happens to $json. When I try $jpath.value[70], I get the expected answer, but $json[70] doesn't exist. In fact, I tried it without the function:
$jpath = [ref]$json.commontokens.search.tokens.token
$jpath.value += $newItem
But it still doesn't work. Am I doing the referencing wrong? Or does it have something to do with the keys?
So, I don't really understand it, but I managed to get it to work.
In adder, I changed the recursive line from
([ref]$j.value.$first)
to
([ref]$($jvalue.value.$first))
I also added a return to make it more obvious I was doing recursion.
For some reason, I still couldn't do $jpath.value += $newItem; However by removing $token from $jpath, $jpath.value.token += $newItem works.
So instead of adding all the strings from stringlist, I skipped the last one.
Adder was changed to skip the last string:
($stringList -ne $null)
was changed to
($stringList-ne $stringList.list.last)
where $stringlist is actually just a node now (I should probably change the name). So the final code is $jpath.value.($stringList.Last.value) += $newItem.
I guess I just can't straight up modify $jpath.value? Or something?

$index as a parameter : multiple if statement issue

Please take a look at this function :
function my_func($index_bis) {
if (!is_int($index_bis) || $index_bis > 5 || $index_bis < 0) return;
elseif ($index_bis = 5) : echo 'This';
elseif ($index_bis = 1) : echo 'That';
endif;
}
What's wrong with this? I actually can't understand where is the mistake...
Thank you for your help.
What is this? PHP?
And what are you attempting to do?
How about this:
function my_func($index_bis) {
if (!is_int($index_bis) || $index_bis > 5 || $index_bis < 0){
$str = $index_bis;
}
elseif ($index_bis == 5) {
$str='This';
}
elseif ($index_bis == 1) {
$str='That';
}
return $str;
}
It's pretty atypical to put anything after "return"; and I think "return" stops the function, effectively.
Edit: FOREACH method.
If you are building html from two related variables, FOREACH is a great method for handling them, as you can set a data "key" and "value" for each item in the array.
By default, the "key" in PHP is assigned a number, starting from 0 and progressing through increasing integers. You have the option of naming these keys, instead of using the PHP-assigned default.
So consider setting up your array as such:
$newArray = (
'tab name' => 'label name',
'apples' => 'red',
'oranges' => 'orange',
);
Wherein the item to the left of the "=>" is always the key, and the item to the right is always the value.
Then, you can add more elements to this array in your code by using this line:
$newArray['bananas'] = 'yellow';
Note the key (tab) name, with square brackets (because it is the key name) and single quotes (because it is a string).
Now that you have an array, you can "walk" it using a FOREACH loop and echoing the html. Here is the code:
foreach($newArray as $key => $value) {
echo "<tab>$key</tab> : ";
echo "<label>$value</label>
echo "<br /";
}
This will output the html below:
<tab>tab name</tab> : <label>label name</label><br />
<tab>apples</tab> : <label>red</label><br />
<tab>oranges</tab> : <label>orange</label><br />
<tab>bananas</tab> : <label>yellow</label><br />
Very useful. Have fun!
Note: There are likely better ways to do this, but I'm sharing this one as a simple solution. And also, because you shouldn't go further without understanding both FOREACH and simple arrays.
Note: If you want to incorporate more than two variables, you will need a more complex data structure. In PHP, these are called "multidimensional arrays". Give it a read. Beyond that, there are still more methods for handling data (ie. "objects").

creating table from 2-Dimensional array in perl has different outputs

Hi I am generating table from a 2-Dimensional array in perl.
But the output of my program is different if viewed in browser and viewing page source using developers tool in chrome:
Let me explain-
I have a subroutine to print the table from #RESULT array, the code is below
sub printTableFormattedEmpty {
my #array= #_ ;
print "<table border='0' cellspacing='0' bgcolor='#cfcfcf' cellpadding='0'>\n";
for(my $row_i = 0; $row_i < #array; $row_i++) {
print "<tr style='background-color:#B39DB3;'>\n";
for(my $column_i = 0; $column_i < #{ $array[$row_i] }; $column_i++) {
my $th = ($row_i == 0) ? "th" : "td";
print "</$th>";
print "$array[$row_i][$column_i]";
my $close = ($row_i == 0) ? 'th' : 'td';
print "</$close> \n";
}
print "</tr> \n";
}
print "</table> \n";
}
and i am calling the subroutine as
{
print "Table starts here!\n";
#$RESULT[0]- is array of many elements. u can see in output image
$RESULT[1][0]= 'No Active bookings available for you !';
$RESULT[2][0]= 'Click here to create new Booking !';
&printTableFormattedEmpty(#RESULT);
}
Now here i am not getting the expected output in a table , i am getting different output as shown in 2 figure:
when i inspect element and inspect the table i get:
But when i view page source of the page iam getting output formatted as table as shown in the fig:
I am really confused with this two types of Output, the both images are of the same page without refreshing.
How is this possible!
Did i do any mistake in my program or its something else.
Please Help me with This.
This is a typo!
There is a slash / in your opening HTML tag output.
for(my $column_i = 0; $column_i < #{ $array[$row_i] }; $column_i++) {
my $th = ($row_i == 0) ? "th" : "td";
# V HERE
print "</$th>";
print "$array[$row_i][$column_i]";
my $close = ($row_i == 0) ? 'th' : 'td';
print "</$close> \n";
}
Remove that slash and it will be fine.
As to why your two outputs are different: The HTML inspector shows the DOM structure after it has been parsed by the browser. It does not include invalid elements. Since stray closing elements are not valid, it's likely the parser just omitted them, so they are gone.
Viewing the source code on the other hand shows the real, unparsed code, which contains the wrong markup with the faulty HTML tags included. That is also where I saw the extra slashes. (read: your variable names are badly chosen. You would have seen it yourself had it been something like $open_tag and $closing_tag).

echo a variable from a multidimentional array outside a function

The code below works for a string value but not when I try to access the variable directly.
The data being accessed is a table at http://webrates.truefx.com/rates/connect.html?f=html
My code strips it of tags and put it in an array $row0
And puts it in a function. But I can't get it out. The function is simplified for this question. I intend to concatenate some of the variables inside the function once I find out what I'm doing wrong.
$row0 = array();
include "scrape/simple_html_dom.php";
$url = "http://webrates.truefx.com/rates/connect.html?f=html";
$html = new simple_html_dom();
$html->load_file($url);
foreach ($html->find('tr') as $i => $row) {
foreach ($row->find('td') as $j => $col) {
$row0[$i][$j]= strip_tags($col);
}
}
myArray($row0); //table stripped of tags
function myArray($arr) {
$a = 'hello'; //$arr[0][0]; HELLO will come out but not the variable
$b = $arr[1][0];
$r[0] = $a;
$r[1] = $b;
//echo $r[1]; If the //'s are removed one can see the proper value here but not outside the function.
return $r;
}
$arrayToEcho = myArray($arr);
echo $arrayToEcho[0]; // will echo "first"
I have tried all the suggestions from here:
http://stackoverflow.com/questions/3451906/multiple-returns-from-function
http://stackoverflow.com/questions/5692568/php-function-return-array
Suggestion appreciated please and more info available if required. Thank you very much for viewing.
You need to get the innertext of $col in your loop. Like this:
$row0[$i][$j]= $col->innertext;
The next thing is:
myArray($row0);
This call will correctly return the parsed array; try echoing it and you'll see. But when you do this:
$arrayToEcho = myArray($arr);
...you're referencing to $arr which is a local variable (a parameter, actually) inside your function myArr. So what you probably meant was this:
$arrayToEcho = myArray($row0);
Hope this helps!
UPDATE
Look, I show you what happens when you call a function:

Multidimensional Array insert into Mysql rows

I have an Array (twodimensional) and i insert it into my database.
My Code:
$yourArr = $_POST;
$action = $yourArr['action'];
$mysql = $yourArr['mysql'];
$total = $yourArr['total'];
unset( $yourArr['action'] , $yourArr['mysql'] , $yourArr['total'] );
foreach ($yourArr as $k => $v) {
list($type,$num) = explode('_item_',$k);
$items[$num][$type] = $v;
$pnr= $items[$num][pnr];
$pkt= $items[$num][pkt];
$desc= $items[$num][desc];
$qty= $items[$num][qty];
$price= $items[$num][price];
$eintragen = mysql_query("INSERT INTO rechnungspositionen (artikelnummer, menge, artikel, beschreibung,preis) VALUES ('$pnr', '$qty', '$pkt', '$desc', '$price')");
}
I get 5 inserts in the Database but only the 5th have the informations i want. The firsts are incomplete.
Can someone help me?
Sorry for my english.
check if You have sent vars from browser in array (like
input name="some_name[]" ...
also You can check, what You get at any time by putting var_dump($your_var) in any place in script.
good luck:)
You probably want to have your query and the 5 assignments above that outside of the foreach. Instead in a new loop which only executes once for every item instead of 5 times. Your indentation even suggests the same however your brackets do not.
Currently it is only assigning one value each time and executing a new query. After 5 times all the variables are assigned and the last inserted row finally has everything proper.
error_reporting(E_ALL);
$items = array();
foreach($yourArr as $k => $v) {
// check here if the variable is one you need
list($type, $num) = explode('_item_', $k);
$items[$num][$type] = $v;
}
foreach($items as $item) {
$pnr = mysql_real_escape_string($item['pnr']);
$pkt = mysql_real_escape_string($item['pkt']);
$desc = mysql_real_escape_string($item['desc']);
$qty = mysql_real_escape_string($item['qty']);
$price = mysql_real_escape_string($item['price']);
$eintragen = mysql_query("INSERT INTO rechnungspositionen (artikelnummer, menge, artikel, beschreibung,preis) VALUES ('$pnr', '$qty', '$pkt', '$desc', '$price')");
}
Switching on your error level to E_ALL would have hinted in such a direction, among else:
unquoted array-keys: if a constant of
the same name exists your script will
be unpredictable.
unescaped variables: malformed values
or even just containing a quote which
needs to be there will fail your
query or worse.
naïve exploding: not each $_POST-key
variable will contain the string
item and your list will fail, including subsequent use of $num