Jump to content

Recommended Posts

Hi,

Can you have a function for example

<?php
function Numbers(){
   $SC = 0;
    $FC = 0;
    $countup = 0;
    $countdown = 0;
  
    $countup = array($SC);
    $countdown = array($FC);
}
?>

Then using the global call a variable from the above function

function countupdown(){
global $countup, $countdown;
echo "<center>";
echo "<br></br>";
echo  . "Systems Online = ".$countup;
echo "<br></br>";
echo . "Systems Offline = ".$countdown;
echo "</center>";
}
?>

Or is this bad practice and what is good practice to do what i am trying to achieve.

Link to comment
https://forums.phpfreaks.com/topic/314999-functions-and-using-global-variables/
Share on other sites

Hi Barand,

I have extended your code you kindly changed for me and i am wanting to count how many successful pings i have and how many unsuccessful pings i have using

<td>" . ($successValue == "UP" ? "<img src='/Images/GTick.jpg'>" ."<span style='color:#000000'>". $SC++ ."</span>" : "<img src='/Images/RTick.jpg'>" . "<span style='color:#000000'>".$FC++ ."</span>"). "</td>

then

    $countup = array($SC);
    $countdown = array($FC);

With a separate function

function countupdown(){
global $SC, $FC, $countup, $countdown;
echo "<center>";
echo "<br></br>";
echo "<img src='/Images/GTick.jpg'>". " " . "Systems Online = ".$countup;
echo "<br></br>";
echo  "<img src='/Images/RTick.jpg'>". " ". "Systems Offline = ".$countdown;
echo "</center>";
}

Then possibly use the array count values to get the numbers for the attached image

Count.jpg

Your numbers function doesn't do anything at all.  Get rid of it.  Then tell us what you want to do.

If you want to use the global construct instead of passing values as arguments, you have to declare the vars in each function that you want them to be known, not just one.

Basically the numbers function was only a example to see if I could do what I require.

The $sc (successfully count) and $fc (failed count) increments after each field is populated from an array I would like to count the $sc and $fc numbers using a separate function

Using:

$countup = array($SC);
$countdown = array($FC);

Works fine in my other function but I want to pull $sc and $fc value into my other function populating the number of ok pings and failed pings 

2 hours ago, Jimmy85 said:
$countup = array($SC);
$countdown = array($FC);

Why are you converting $countup and $countdown to arrays. (you can't echo an array) Is you criticalSystems() function being called several times for different sets of systems?

Problem is, I am only seeing a couple of snippets of code with no context as to how and where they are called, which doesn't help me.

Conventional wisdom says "Forget that the global keyword exists". (It can cause more problems than it solves.) Pass values as function arguments.

The two most likely scenarios are these

A ) the functions are called independantly

<?php 

    CriticalSystem();                            // call 1st function 
    countupdown();                               // call 2nd function

    function  CriticalSystem()
    {
        // function definition
    }

    function  countupdown()
    {
        // function definition
    }

?>

B ) the second function is called from within the first function

<?php 

    CriticalSystem();                            // call 1st function 
    

    function  CriticalSystem()
    {
        // function definition
        countupdown();                           // call 2nd function
    }

    function  countupdown()
    {
        // function definition
    }

?>

Which of these applies will determine how the values are passed.

Hi,

As promised here is the code this is my functions.php:

<?php
//$GLOBAL Variables
//$GLOBALS['SC'] = 0;
//$GLOBALS['FC'] = 0;
//$GLOBALS['countup'] = 0;
//$GLOBALS['countdown'] = 0;


function completedJC(){
//completed call count
include 'SqlConn.php';	
$sql = "Select Count(Status) from EXCELMACRO...Jobs$ where Status = 'Completed'";
			$stmt = $conn->query($sql);
			$stmt->execute();
    		$resultCompleted = $stmt->fetchColumn();
			echo $resultCompleted;
}

function inprogressJC(){
//In-progress call count
include 'SqlConn.php';	
$sql = "Select Count(Status) from EXCELMACRO...Jobs$ where Status = 'In-Progress'";
			$stmt = $conn->query($sql);
			$stmt->execute();
    		$resultInprogress = $stmt->fetchColumn();
			echo $resultInprogress;

}

function OnHoldJC(){
//On-hold call count
include 'SqlConn.php';	
$sql = "Select Count(Status) from EXCELMACRO...Jobs$ where Status = 'ON-HOLD'";
			$stmt = $conn->query($sql);
			$stmt->execute();
    		$resultOnHold = $stmt->fetchColumn();
			echo $resultOnHold;
}

function CriticalSystem(){
     //array for critical devices
    //Black #000000
    //White #FFFFFF
    $SC = 0;
    $FC = 0;
    $countup = 0;
    $countdown = 0;
    
 $systems = array( 
    array('ip' => '192.168.9.254', 'name' => 'Tech Swtich'), 
    array('ip' => '192.168.9.205', 'name' => 'Printer'),
    array('ip' => '192.168.9.200', 'name' => 'Sales Printer'),
    array('ip' => '192.168.9.201', 'name' => 'Admin Printer'),
    array('ip' => '192.168.9.1', 'name' => 'KVM'),
    array('ip' => '192.168.9.2', 'name' => 'Office Data 24 Port'),
    array('ip' => '192.168.9.3', 'name' => 'Office Data 48 Port'),
    array('ip' => '192.168.9.4', 'name' => 'Office Voice 48 Port'),
    array('ip' => '192.168.9.7', 'name' => 'Warehouse Switch'),
    array('ip' => '192.168.9.13', 'name' => 'Foundry Canteen Switch'),
    );
    //Result to search for to give success result
    $good = "Received = 1";
    $successValue;
    
    //troubleshooting to see if being re-freshed
    //echo "<h1>Site Status  ".date("h:i:s")."</h1>";
   
    echo "<table border='0' class='table'>";
    // foreach loop to ping IP and check if alive or dead & dispaly result
    foreach ($systems as $ip) {
        unset($result);
        $successValue = "DOWN";
        exec("ping -n 1 $ip[ip]", $result);
        foreach($result as $line) {
            if (strpos($line,$good) == TRUE){
                $successValue = "UP";
                //$count = $successValue;
            }
        }
        
        echo "<tbody>
                 <tr>
                    <td>IP Address: {$ip['ip']}</td>
                    <td>Unit Name: {$ip['name']}</td>
                 </tr>
                 <tr>
                    <td>Status is: $successValue</td>
                    <td>" . ($successValue == "UP" ? "<img src='/Images/GTick.jpg'>" ."<span style='color:#000000'>". $SC++ ."</span>" : "<img src='/Images/RTick.jpg'>" . "<span style='color:#000000'>".$FC++ ."</span>"). "</td>
                  </tr>
             </tbody>
             ";
     }
    echo"</table>";
     //debug dispaly full result of ping request
    //var_dump($result);
    $countup = array($SC);
    $countdown = array($FC);
    print_r($countup);
    //Print_r($countdown);
}

function countupdown(){
global $SC, $FC, $countup, $countdown;
echo "<center>";
echo "<br></br>";
echo "<img src='/Images/GTick.jpg'>". " " . "Systems Online = ".$countup;
echo "<br></br>";
echo  "<img src='/Images/RTick.jpg'>". " ". "Systems Offline = ".$countdown;
echo "</center>";
print_r($countup);
}

?>

 Here is my index.php

<!doctype html>
<html lang="en">
<?php //Function Scripts
//SqlConn 
include 'SqlConn.php';
//Completed Job Count
include 'Functions.php';
?>
<head>
  <title>Support Desk</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="description" content="">
  <meta name="author" content="James Stirling">
  <meta name="generator" content="Hugo 0.98.0">
  <meta http-equiv="refresh" content="5" 
  
  <link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
  <link rel="icon" type="image/png" sizes="32x32" href="favicon/favicon-32x32.png">
  <link rel="icon" type="image/png" sizes="16x16" href="favicon/favicon-16x16.png">
  <link rel="manifest" href="favicon/site.webmanifest">
  <link rel="mask-icon" href="favicon/safari-pinned-tab.svg" color="#5bbad5">
  <meta name="msapplication-TileColor" content="#da532c">
  <meta name="theme-color" content="#ffffff">

  <link rel="canonical" href="https://getbootstrap.com/docs/5.2/examples/features/">

  <link href="/docs/5.2/dist/css/bootstrap.min.css" rel="stylesheet"
    integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous">
 
</head>
  <!-- <title>Support Desk</title> -->
<body>
  <style>
    .btn-primary {
      --bs-btn-color: #fff;
      --bs-btn-bg: #007A53;
      --bs-btn-focus-shadow-rgb: 49, 132, 253;
      --bs-btn-active-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125)
    }

    .b-divider {
      height: 3rem;
      background-color: rgba(0, 0, 0, .1);
      border: solid rgba(0, 0, 0, .15);
      border-width: 1px 0;
      box-shadow: inset 0 .5em 1.5em rgba(0, 0, 0, .1), inset 0 .125em .5em rgba(0, 0, 0, .15);
    }
  </style>
  <main>
    <!-- Calls Logged -->
    <div class="container px-4 py-5" id="hanging-icons">
      <center>
        <h2 class="pb-2 border-bottom">Hargreaves Foundry & Drainage Critical System Status Page</h2>
      </center>
    </div>
    <div class="container px-4 py-5" id="hanging-icons">
      <h2 class="pb-2 border-bottom">Open Calls: View all status of IT faults</h2>
      <div class="row g-4 py-5 row-cols-1 row-cols-lg-3">
        <div class="col d-flex align-items-start">
          <div
            class="icon-square bg-light text-dark d-inline-flex align-items-center justify-content-center fs-4 flex-shrink-0 me-3">
          </div>
          <div>
            <h2>Completed: (<?php completedJC();?>)</h2>
            <p>Number of all calls that have been completed for each department and staff member.</p>
                     </div>
        </div>
        <div class="col d-flex align-items-start">
          <div
            class="icon-square bg-light text-dark d-inline-flex align-items-center justify-content-center fs-4 flex-shrink-0 me-3">
          </div>
          <div>
            <h2>In-Progress: (<?php inprogressJC();?>)</h2>
            <p>Number of open calls and the progress of the call for a department or staff member.</p>
             </div>
        </div>
        <div class="col d-flex align-items-start">
          <div
            class="icon-square bg-light text-dark d-inline-flex align-items-center justify-content-center fs-4 flex-shrink-0 me-3">
          </div>
          <div>
            <h2>ON-HOLD: (<?php OnHoldJC();?>)</h2>
            <p>Number of calls placed ON-HOLD for what ever reason or awaiting input from a third party.</p>
                    </div>
        </div>
      </div>
    </div>
    <div class="b-divider"></div>
    <!-- Critical Systems -->
    <div class="container px-4 py-5" id="hanging-icons">
      <h2 class="pb-2 border-bottom">Critical Systems Online\Offline Count</h2>
       
<?php
countupdown();
?>
 
    </div>
    <div class="b-divider"></div>

    <!-- Critical Systems -->
    <div class="container px-4 py-5" id="hanging-icons">
      <h2 class="pb-2 border-bottom">Critical Systems Ping Check</h2>
       
<?php
CriticalSystem();
?>
 
    </div>
</main>

  <div class="b-divider"></div>
  <script src="/docs/5.2/dist/js/bootstrap.bundle.min.js"
    integrity="sha384-pprn3073KE6tl6bjs2QrFaJGz5/SUsLqktiwsUTF55Jfv3qYSDhgCecCxMW52nD2"
    crossorigin="anonymous"></script>
</body>
<footer class="py-3 my-4">
  <ul class="nav justify-content-center border-bottom pb-3 mb-3">
  </ul>
  <p class="text-center text-muted">© 2022 Hargreaves Foundry & Drainage, Inc</p>
  <center>
    <img src="docs/5.2/images/image1.png" style="width:40px;height:40px;margin-top:20px" />
  </center>
</footer>

</html>

Any question please ask.

Thanks James

First you are going to have to bear some criticism of your code :)

  • DO NOT connect to the server every time you call a function. Connect once at the top of index.php an pass the connection in the function calls. Connections are slow and you will overburden your server with connections
  • You don't need 3 function calls to get the status totals - one will suffice
  • You don't execute() after query(), execute() is for prepared statements.
  • Don't put a closing ?> at end of included php files

Lecture over, here's how I would do it

(skeleton) index.php

<?php
require 'SqlConn.php';

$SC = 0;
$FC = 0;

// get status counts and store counts in an array

$statusCounts = JC($conn);                                        // pass $conn to function

// output status counts

echo "<h2>Completed : {$statusCounts['Completed']}</h2>";

echo "<h2>In-Progress : {$statusCounts['In-Progress']}</h2>";

echo "<h2>On-Hold : {$statusCounts['ON_HOLD']}</h2>";

// check critical systems

CriticalSystem( $SC, $FC );

// output system success counts

countupdown($SC, $FC);
?>

functions.php

<?php

function JC($conn)                                                              // pass $conn to function
{
    $sql = "Select Status
                 , Count(Status) as total
            from EXCELMACRO...Jobs$ 
            group by Status
            ";
    $stmt = $conn->query($sql);
    $resultCompleted = $stmt->fetchAll();
    return array_column($resultCompleted, 'total', 'Status');                   // return array of totals bt status
}


function CriticalSystem( &$SC, &$FC )                                           // pass count variables by reference
{
     //array for critical devices
        
 $systems = array( 
    array('ip' => '192.168.9.254', 'name' => 'Tech Swtich'), 
    array('ip' => '192.168.9.205', 'name' => 'Printer'),
    array('ip' => '192.168.9.200', 'name' => 'Sales Printer'),
    array('ip' => '192.168.9.201', 'name' => 'Admin Printer'),
    array('ip' => '192.168.9.1', 'name' => 'KVM'),
    array('ip' => '192.168.9.2', 'name' => 'Office Data 24 Port'),
    array('ip' => '192.168.9.3', 'name' => 'Office Data 48 Port'),
    array('ip' => '192.168.9.4', 'name' => 'Office Voice 48 Port'),
    array('ip' => '192.168.9.7', 'name' => 'Warehouse Switch'),
    array('ip' => '192.168.9.13', 'name' => 'Foundry Canteen Switch'),
    );
    //Result to search for to give success result
    $good = "Received = 1";
    
    //troubleshooting to see if being re-freshed
    //echo "<h1>Site Status  ".date("h:i:s")."</h1>";
   
    echo "<table border='0' class='table'>";
    // foreach loop to ping IP and check if alive or dead & dispaly result
    foreach ($systems as $ip) {
        unset($result);
        $successValue = "DOWN";
        exec("ping -n 1 $ip[ip]", $result);
        foreach($result as $line) {
            if (strpos($line,$good) == TRUE){
                $successValue = "UP";
            }
        }
        
        echo "<tbody>
                 <tr>
                    <td>IP Address: {$ip['ip']}</td>
                    <td>Unit Name: {$ip['name']}</td>
                 </tr>
                 <tr>
                    <td>Status is: $successValue</td>
                    <td>" . ($successValue == "UP" ? "<img src='/Images/GTick.jpg'>" ."<span style='color:#000000'>". $SC++ ."</span>" : "<img src='/Images/RTick.jpg'>" . "<span style='color:#000000'>".$FC++ ."</span>"). "</td>
                  </tr>
             </tbody>
             ";
     }
    echo"</table>";

    $FC = count($systems) - $SC;
}

function countupdown($countup, $countdown)                                   // pass counts to function
{
    echo "<center>";
    echo "<br></br>";
    echo "<img src='/Images/GTick.jpg'>". " " . "Systems Online = ".$countup;
    echo "<br></br>";
    echo  "<img src='/Images/RTick.jpg'>". " ". "Systems Offline = ".$countdown;
    echo "</center>";
}

 

  • 2 weeks later...

Yes.

Arrange your page so all php code comes first followed by the html section which does all the output

<?php
	// call function to populate $statusCounts array
    // store anything that requires outputting in variables
?>
<html>
  <body>
     <h2>Completed: <?=$statusCounts['Completed']?></h2>
     etc
  </body>
</html>

 

Sorry Barand,

I am confused by what your saying,  basically i would like to keep the array as it is but move the System online and system offline count above the array at the top of page.

Sorry to be annoying but I am trying to self teach PHP for a project.

7 hours ago, Jimmy85 said:

I am confused by what your saying,  basically i would like to keep the array as it is but move the System online and system offline count above the array at the top of page.

Here is a simple example of what I was trying to explain. The elements to be output are created in the php section and stored in variables.

Because they are now stored, they can be output to the page in any order you want (in this case completely different from the order they were calculated)

Code

<?php
 
$votes = [ 'Archie' => 203,
           'Ben'    => 406,
           'Carol'  => 584,
           'David'  => 398,
           'Emily'  => 259
         ];

$tdata = '';
$total_votes = 0;
foreach ($votes as $candidate => $tot) {
    $tdata .= "<tr><td>$candidate</td><td>$tot</td></tr>";
    $total_votes += $tot;
}
$max_votes = max($votes);
$winner = array_keys($votes, $max_votes)[0];
$win_pcent = number_format($max_votes/$total_votes*100, 0);
$result = "Winner is $winner with $win_pcent% of the votes";

?> 
<!DOCTYPE html>
<html lang='en'>
<head>
<title>sample</title>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>
<script type='text/javascript'>
</script>
<style type='text/css'>
    body {
        background-color: #fbf7e9;
    }
</style>
</head>
<body>
    <h2><?= $result ?></h2>
    <h3>Total votes cast was <?= $total_votes ?></h3>
    <table style='width: 300px;'>
        <tr><td><b>Candidate</b></td><td><b>No of votes</b></td></tr>
        <?= $tdata ?>
    </table>
</body>
</html>

Output

image.png.4542b7f18af19f7449e0a95ecf9c18b3.png

  • 3 months later...

I am a bit confused on how to get the functions sorted as your example only show one line of html in $tdata where I have multiple lines for example how would i do 

$table = <tbody>

              <tr>

                 <td>IP Address: {$ip['ip']}</td>

                 <td VALIGN = Middle Align = Center>Unit Name: {$ip['name']}</td>

              </tr>

              <tr>

                 <td>Status is: $successValue</td>

                 <td VALIGN = Middle Align = Center>" . ($successValue == "UP" ? "<img src='/Images/GTick.jpg'>" ."<span style='color:#FFFFFF'>". $SC++ ."</span>" : "<img src='/Images/RTick.jpg'>" . "<span style='color:#FFFFFF'>".$FC++ ."</span>"). "</td>

               </tr>

          </tbody>

          ";

  }

"</table>";

 

Like your $tdata variable

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.