How do I write code without a foreach loop? - php

How do I write this code without a foreach loop? I want to fetch the data from the database, but the key and value are stored in the database.
<?php
$options = get_payment_mode_options();
foreach ($options as $key => $value)
{
echo isset($form_data["personal_info"]) && $form_data["personal_info"]->payment_mode == $key ? $value : "";
}
?>
get_payment_mode_options() is function in helper,
function get_payment_mode_options()
{
return array(
"o" => "Online Payment",
"c" => "Cheque Payment"
);
}

Check this,
$options = get_payment_mode_options();
$paymentmode = isset($form_data["personal_info"]) ? $form_data["personal_info"]->payment_mode : '';
echo $options[$paymentmode];
helper function
function get_payment_mode_options()
{
return array(
"o" => "Online Payment",
"c" => "Cheque Payment"
);
}

<?php
function get_payment_mode_options()
{
return array(
"o" => "Online Payment",
"c" => "Cheque Payment"
);
}
// make a new function
function get_your_result($your_key)
{
if (!$your_key) {
return "";
}
$options = get_payment_mode_options();
if(!array_key_exists($your_key,$options)){
return "";
}
return $options[$your_key];
}
// dummy for test
$form_data["personal_info"] = new stdClass();
$form_data["personal_info"]->payment_mode = "o";
$k = $form_data["personal_info"]->payment_mode;
// ~dummy for test
// echo result
echo "----".PHP_EOL;
echo get_your_result($k).PHP_EOL;
echo "----".PHP_EOL;

Related

Inserting data from session using codeigniter

I'm just practicing using session in Codeigniter and i've got a Problem here's my controller
public function ajax_Addfees()
{
if($this->input->is_ajax_request())
{
$input = $this->input->post();
if($this->session->userdata('html')){
$html = $this->session->userdata('html');
}
$id = explode($input['fno']);
$html[$id] = ['amount' => $input['amount'], 'oldamount' => $input['deduction']];
$this->session->set_userdata('html', $html);
}
}
public function savetuition()
{
$this->Tuition_model->savefees();
redirect('tuitionsetup_con');
}
This is my model
public function savefees()
{
$fees = $this->session->userdata('html');
$feeslist = [];
if( !empty($fees) ) {
foreach ($fees as $key =>$value) {
array_push($feeslist, [
'amount' => $value['amount'],
'oldamount' => $value['oldamount'],
'f_no' => $key,
'sy_no' => $this->session->userdata('sy'),
'level_no' => $this->session->userdata('lvl'),
'id' => $this->session->userdata('id')
]);
$this->db->insert_batch('tuition', $feeslist);
} }
}
Well what I'm trying to do is to save data from session->set_userdata('html') to my database using codeigniter.
There's no error but it doesn't save data to database
You need to modify your model as:
public function savefees() {
$fees = $this->session->userdata('html');
$feeslist = array();
if( !empty($fees) ) {
foreach ($fees as $key =>$value) {
$feeslist[$key]["amount"] = $value['amount'];
$feeslist[$key]["oldamount"] = $value['oldamount'];
$feeslist[$key]["f_no"] = $key;
$feeslist[$key]["sy_no"] = $this->session->userdata('sy');
$feeslist[$key]["level_no"] = $this->session->userdata('lvl') ;
$feeslist[$key]["id"] = $this->session->userdata('id') ;
}
}
$this->db->insert_batch('tuition', $feeslist);
}

"No data supplied for parameters in prepared statement" global insert function

I wrote an global function that getting array with keys and values, and inserting it to mysql db. something like this:
function insert_to_db($table, $data, $is_using_id) {
// I'm connecting to db before this code.
global $mysqli;
// .. Checking for errors ..
// .. if using id, remove the id from the values like this:
$columns = array_keys($data);
$values = array_values($data);
if ($is_using_id == true) {
unset($values[0]);
// Reorder the array after unset()
$values = array_merge($values);
}
// ..
// Generating text for use at the mysqli::prepare
$columns_text = "";
$i = 0;
while ($i < count($columns)) {
$column = $columns[$i];
if ($i == 0) {
$columns_text = $column;
} else {
$columns_text = $columns_text.", ".$column;
}
$i++;
}
unset($i);
unset($column);
$values_text = "";
// b_p_f is the $types string for mysqli-stmt::bind_param
$b_p_f = "";
// Generating text for use at the mysqli::prepare
$i = -1;
while ($i < count($values)) {
echo "\$i equals to {$i}<br>";
if ($is_using_id == true && $i == -1) {
// Null because id is calculated automatically by mysql
$values_text = "NULL";
} else if ($is_using_id == false && $i == 0) {
$value = $values[$i];
$values_text = "?";
if (is_numeric($value))
{
$b_p_f = 'i';
} else {
$b_p_f = 's';
}
} else {
$value = $values[$i];
$values_text = $values_text.", ?";
if (is_numeric($value))
{
echo "Value: {$value} Found as numberic<br>";
$b_p_f = $b_p_f.'i';
} else {
echo "Value: {$value} Found as non-numberic<br>";
$b_p_f = $b_p_f.'s';
}
}
$i++;
}
unset($i);
unset($value);
echo "b_p_f:";
var_dump($b_p_f);
echo " values:";
var_dump($values);
$stmt = $mysqli->prepare("INSERT INTO ".$table." (".$columns_text.") VALUES (".$values_text.")");
if (!$stmt) {
return array("error"=>"true", "error_mysqli"=>$mysqli->error, "MORE"=>"INSERT INTO ".$table." (".$columns_text.") VALUES (".$values_text.")");
}
$stmt->bind_param($b_p_f, $values);
if ($stmt->execute()) {
return array("error"=>"false", "inserted_id"=>$mysqli->insert_id);
} else {
return array("error"=>"true", "error_stmt"=>$stmt->error, "MORE"=>"INSERT INTO ".$table." (".$columns_text.") VALUES (".$values_text.")");
}
}
Then I am calling to the function:
function hash_password($password) {
$options = [ 'cost' => 12 ];
return password_hash($password, PASSWORD_BCRYPT,$options);
}
$data = array(
"ID" => NULL,
"first_name" => "Alexander",
"last_name" => "Margolis",
"email" => "shay24590#gmail.com",
"username" => "smartDonkey",
"password" => "Incorrect",
"birthday" => "12-12",
"date_added" => time(),
"total_points" => 0,
"cafe_added" => 0,
"review_placed"=> 0);
$data["password"] = hash_password($data["password"]);
var_dump ( insert_to_db("user", $data, true) );
And I see on the screen
array(3) {
["error"]=> string(4) "true"
["error_stmt"]=> string(53) "No data supplied for parameters in prepared statement" ["MORE"]=> string(178) "..."
}
Why am I getting this? What is the problem?
Also, If I pass the value instead of ? to the mysql::prepare, it works! So - it means that the problem is with mysqli stmt bind_param..
I know that this question similar to others, but I didn't found one that helps my problem. and sorry for my english and for the long function. thank you!
I've moved to PDO, and instead of calling $stmt->bind_param($b_p_f, $values); you can call $pdo_stmt->execute($values) where $values is an Array.

PHP to delete cookie in php class

I am about to control my pages content. so that I need add or delete sessions/cookies. I maked a class that is working fine but in the cookie issue, it is not working as well. I checked with firefox 18 in windows7, and ubuntu 12.04 LTS. the cookies are not deleted using
setcookie(name, '', time()-9600)
foreach($this->_ck as $cookie)
{
$hrs=0;
if($plus)
{
$hrs=3600*$cfg_cookie_time;
}
//setcookie('testcookie13', '', time()-3600*6);
header("Set-Cookie: ".$cookie."=deleted; expires=Sun, 01-Jul-2012 08:59:12 GMT;");
}
etc...
My class is:
<?php
class headers{
var $new;
var $vars;
var $ss;
var $ck;
var $_ss;
var $_ck;
var $error;
var $catchs;
function _construct()
{
$this->new=false;
$this->error=false;
$this->ss=array();
$this->ck=array();
$this->_ss=array();
$this->_ck=array();
$this->catchs=true;
return $this->catchs;
} //f
function headers($hs = array(
"set" => array(
"ss" => array(),
"ck" => array()
)
))
{
if(isset($hs['send']))
{
$this->new=$hs['send'];
$this->catchs=true;
}
if(is_array($hs['set']))
{
if(is_array($hs['set']['ss']))
{
$this->ss = $hs['set']['ss'];
}
if(is_array($hs['set']['ck']))
{
$this->ck = $hs['set']['ck'];
}
}
if(is_array($hs['unset']))
{
if($hs['unset']['ss'])
{
$this->_ss = $hs['unset']['ss'];
}
if(is_array($hs['unset']['ck']))
{
$this->_ck = $hs['unset']['ck'];
}
}
return $this->catchs;
} //f
function send(
$cfg_cookie_time=6,
$plus=true
)
{
$cookie='';
if(is_array($this->ss))
{
session_start();
foreach($this->ss as $session){
$_SESSION['session'] = $session;
}
}
if($this->_ck)
{
foreach ($_COOKIE as $name => $value) {
setcookie($name, '', 1);
}
}
if($this->ck)
{
foreach($this->ck as $cookie => $val)
{
//$this->ck=$cookie.$val;
$hrs=0;
if($plus)
{
$hrs=3600*$cfg_cookie_time;
}
header("Set-Cookie: ".$cookie."=".$val."; path=/; domain=".$_SERVER['HTTP_HOST']."; expires=".gmstrftime("%A, %d-%b-%Y %H:%M:%S GMT;", time()+$hrs));
}
}
if($this->new)
{
header("location: ".$this->new);
$this->catchs=false;
}
header("X-Powered-By: PHP ".phpversion()."/FxPHP");
//header("HTTP/1.0 404 Not Found");
return $this->ck;
} //f
} // class
setcookie('H', '', -3600);
/*$hr = new HEADERS( array
(
"set" => array
(
"ck"=> array(),
"ss"=> array()
),
"unset" => array
(
"ck"=> array
(
"H" => "H"
),
"ss"=> array()
)
)
);
print_r( $_COOKIE).print_r($hr->send());
/*
" f" => "" ,
" sf" => "",
"my"=> "" ,
print_r(getallheaders());
print_r(setcookie('sd', 'dsds', 3600*6));
*/
?>
Can you any help?
Try it:
<?php
function del_cookie($_cookie = array())
{
foreach($_cookie as $k => $kv)
{
setcookie($k, '', time()-3600);
}
return;
}
function add_cookie($_cookie)
{
foreach($_cookie as $k => $kv)
{
setcookie($k, $kv, time()+3600*24*6);
}
return;
}
class headers{
var $new;
var $vars;
var $ss;
var $ck;
var $_ss;
var $_ck;
var $_ak;
var $_dk;
var $error;
var $catchs;
function _constract()
{
$this->new=false;
$this->error=false;
$this->ss=array();
$this->ck=array();
$this->_ss=array();
$this->_ck=array();
$this->catchs=true;
$this->_ak = false;
$this->_dk = false;
return $this->catchs;
} //f
function headers($hs = array(
"set" => array(
"ss" => array(),
"ck" => array()
)
))
{
if(isset($hs['send']))
{
$this->new=$hs['send'];
$this->catchs=true;
}
if($hs['set']['ck']['true'])
{
$this->ck = $hs['set']['ck'];
$this->_ak = true;
}
/*if($hs['unset']['ss'])
{
$this->_ss = $hs['unset']['ss'];
}
*/
if($hs['unset']['ck']['true'])
{
$this->_ck = $hs['unset']['ck'];
$this->_dk = true;
}
return $this->catchs;
} //f
function send(
$cfg_cookie_time=6,
$plus=true
)
{
if(is_array($this->ss))
{
session_start();
foreach($this->ss as $session){
$_SESSION['session'] = $session;
}
}
if($this->_dk)
{
del_cookie($this->_ck);
}
if($this->_ak)
{
add_cookie($this->ck);
}
if($this->new)
{
header("location: ".$this->new);
$this->catchs=false;
}
header("X-Powered-By: PHP ".phpversion()."/FxPHP");
//header("HTTP/1.0 404 Not Found");
return $this->catchs;
} //f
} // class
$hr = new HEADERS( array
(
"set" => array
(
"ck"=> array(
"true" => ""
),
"ss"=> array
(
"true" => "")
),
"unset" => array
(
"ck"=> array
(
"true" => "YES",
"Test" => "1"
),
"ss"=> array
(
"true" => "")
)
)
);
print_r( $_COOKIE).print_r($hr->send());
/*
" f" => "" ,
" sf" => "",
"my"=> "" ,
print_r(getallheaders());
print_r(setcookie('sd', 'dsds', 3600*6));
*/
?>
One error I see in your code is
function _constract()
which should be
function __construct()
setcookie($cookie_name, null, null);
Will delete a cookie no matter what. Use that in plain php in the beginning of a script before any logic to verify that. If you're using this and your cookies are not being deleted you're either using xml requests or you have some issues in your logic. Good luck!

Simple array access and manipulation methods

Hy, I designed an array, and I need some help because I've got aaaloot of headaches. Can anyone give me a simple idea how to work with this in a simple way?
Most of the errors when I try to add some values in my array are array offset error.
My array:
$info = array
(
"id" => "",
"city" => "",
"university" => array
(
"name" => "",
"address" => "",
"phone" => "",
"fax" => "",
"email" => "",
"website" => "",
"type" => "",
"faculty" => array
(
"name" => "",
"adress" => "",
"phone" => "",
"fax" => "",
"email" => "",
"website" => "",
"type" => "",
)
)
);
CODE:
<?php
// HTML DOM PARSER LIBRARY
include('hdp.php');
//error_reporting(false);
/*
* Returns an array with field associative name and
* extracted value, using a specified delimiter.
*/
function extractField($str, $delim)
{
$val = '';
// All possible fields
$posFlds = array
(
'Adresa' => 'address',
'Telefon' => 'phone',
'Fax' => 'fax',
'Email' => 'email',
'Website' => 'website',
'Tip' => 'type'
);
foreach($posFlds as $fldName => $assocName)
{
if(strstr($str,$fldName))
{
$val = #explode($delim,$str);
if (!$val[1])
{
print 'Delimiter `'.$delim.'` not found!';
return false;
}
return array($assocName, $val[1]);
}
}
return false;
}
// DB->Table query structure
$info = array
(
"id" => "",
"city" => "",
"university" => array
(
"name" => "",
"address" => "",
"phone" => "",
"fax" => "",
"email" => "",
"website" => "",
"type" => "",
"faculty" => array
(
"name" => "",
"adress" => "",
"phone" => "",
"fax" => "",
"email" => "",
"website" => "",
"type" => "",
)
)
);
// City identifier
$cityid = 0;
// Rows, columns and deep identifiers
$i = 0; $j = 0; $k = 0;
// Base, secondary and third crawl url
$baseUrl = 'XXX';
$secondaryUrl = ''; $thirdUrl ='';
// Html contents without stripped tags (as is)
$htmlCu = file_get_html($baseUrl);
$htmltUn = ''; $htmltFa = '';
// Selectors for third level deep check
$selectCu = $htmlCu->find('td[width="100%"] table td');
$selectUn = ''; $selectFa ='';
// Text formats (raw and cleaned)
$rtext =''; $ftext = '';
// Contoare
$a=0; $b=0; $c=0;
// Select each row from parent td -> child table -> child td
foreach($selectCu as $row)
{
// Skip first row result
if($i != 0)
{
$rtext = $row->plaintext;
$ftext = trim($rtext,' • ');
if($ftext != '-')
{
// If string contains a dot it is a city
if(strstr($rtext, '•'))
{
print "CITY = ".$ftext."<br>";
$cityid++;
$info[$a]["city"] = $ftext;
}
// If string is not a city, then is a university
else
{
$info[$a]["city"][$b]['university']['name'] = $ftext;
echo "<b>----ID [".$i."]; NAME:</b> ".$ftext."<br>";
$secondaryUrl = $row->find('a',0)->href;
$htmlUn = file_get_html($secondaryUrl);
$selectUn = $htmlUn->find('td[width="100%"] table tr');
foreach($selectUn as $col)
{
// Skip first row result
if($j != 0)
{
$rtext = $col->plaintext;
$ftext = trim($rtext,' • ');
echo "--------ID[".$j."] NAME: <b>".$ftext."</b>; TYPE: ".gettype($col)."<br>";
// key 0 -> associative name; key 1 -> value
$field = extractField($ftext,': ');
if($field)
{
echo "--------<b>Field name:</b> ".$field[0]."<b>, value:</b> ".$field[1]."<br>";
}
/////////////////////////////TESTTTTTT ZONEEEEEEEEEEEEEEE/////////////////////////////
// If string contains a dot it is a faculty
if(strstr($rtext, '•'))
{
$thirdUrl = $col->find('a',0)->href;
$htmlFa = file_get_html($thirdUrl);
$selectFa = $htmlFa->find('td[width="100%"] table tr');
foreach($selectFa as $deep)
{
$rtext = $deep->plaintext;
$ftext = trim($rtext,' • ');
//echo "------------id[".$k."] <-> <b>".$ftext."</b> <-> ".gettype($deep)."<br>";
$field = extractField($ftext,': ');
if($field)
{
echo "------------<b>Field name:</b> ".$field[0]."<b>, value:</b> ".$field[1]."<br>";
}
$k++;
}
echo "<br><br>";
}
}
$j++;
}
echo "<br><br>";
}
}
}
$i++;
if($cityid == 2) break;
}
print "<h1>".($i-1)."</h1>";
print_r($info);
You are accessing the array the wrong way in those calls:
$info[$a]["city"] = $ftext;
$info[$a]["city"][$b]['university']['name'] = $ftext;
Correct would be:
$info["city"] = $ftext;
$info["city"]['university']['name'] = $ftext;
It seems you want to handle multiple $info-arrays. For this you have to create an array of those info-arrays.
Final and working code, if anyone fiind this usefull:
// HTML DOM PARSER LIBRARY
include('hdp.php');
error_reporting(true);
// Session to know what last city was
session_start();
if (!$_SESSION['LAST']) $_SESSION['LAST'] = NULL;
/*
* Returns an array with field associative name and
* extracted value, using a specified delimiter.
*/
function extractField($str, $delim)
{
$val = '';
// All possible fields
$posFlds = Array
(
'Adresa' => 'address',
'Telefon' => 'phone',
'Fax' => 'fax',
'Email' => 'email',
'Website' => 'website',
'Tip' => 'type'
);
foreach($posFlds as $fldName => $assocName)
{
if(strstr($str,$fldName))
{
$val = #explode($delim,$str);
if (!$val[1])
{
print 'Delimiter `'.$delim.'` not found!';
return false;
}
return array($assocName, $val[1]);
}
}
return false;
}
// Trying to connect to local server
$conn = mysqli_connect("localhost","root","","educatie") or die("Could not connect to MySQL server!");
if (mysqli_connect_errno($conn))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// DB->Table Query structure
$info = Array
(
"city" => Array
(
"name" => "",
"university" => Array
(
"name" => "",
"address" => "",
"phone" => "",
"fax" => "",
"email" => "",
"website" => "",
"type" => "",
"faculty" => Array
(
"name" => "",
"adress" => "",
"phone" => "",
"fax" => "",
"email" => "",
"website" => "",
"type" => "",
)
),
)
);
// City identifier
$cityid = 0;
// Rows, columns and deep identifiers
$i = 0; $j = 0; $k = 0;
// Base, secondary and third crawl url
$baseUrl = 'http://infoportal.rtv.net/informatii_universitati.html';
$secondaryUrl = ''; $thirdUrl ='';
// Html contents without stripped tags (as is)
$htmlCu = file_get_html($baseUrl);
$htmltUn = ''; $htmltFa = '';
// Selectors for third level deep check
$selectCu = $htmlCu->find('td[width="100%"] table td');
$selectUn = ''; $selectFa ='';
// Text formats (raw and cleaned)
$rtext =''; $ftext = '';
// Ignore tokens
$banned = array(" ","•","""," ");
// Counters A, B and C
$a=0; $b=0; $c=0;
// Temporary variables
$tmpVar = '';
// Select each row from parent td -> child table -> child td
foreach($selectCu as $row)
{
// Skip first row result
if($i != 0)
{
$rtext = $row->plaintext;
$ftext = trim($rtext,' • ');
if($ftext != '-')
{
// If string contains a dot it is a city
if(strstr($rtext, '•'))
{
if(($_SESSION['LAST'] !== $ftext) && ($_SESSION['LAST'] !== NULL)) continue;
print "<h1>-> Oras: ".$ftext."</h1><br>";
echo "SESSION:".$_SESSION['LAST']."|<br />";
$tmpVar = $ftext;
}
// If string is not a city, then is a university
else
{
$a--;
$info[$a]['city']['name'] = $tmpVar;
$info[$a]['city']['university'][$b]['name'] = $ftext;
$secondaryUrl = $row->find('a',0)->href;
$htmlUn = file_get_html($secondaryUrl);
$selectUn = $htmlUn->find('td[width="100%"] table tr');
foreach($selectUn as $col)
{
// Skip first row result
if($j != 0)
{
$rtext = $col->plaintext;
$ftext = trim($rtext,' • ');
// key 0 -> associative name; key 1 -> value
$field = extractField($ftext,': ');
if($field)
{
if(strstr($field[1],'de stat'))
$info[$a]['city']['university'][$b][$field[0]] = 'de stat';
else
$info[$a]['city']['university'][$b][$field[0]] = $field[1];
}
/////////////////////////////TESTTTTTT ZONEEEEEEEEEEEEEEE/////////////////////////////
// If string contains a dot it is a faculty
if(strstr($rtext, '•'))
{
$tempVar = trim(str_replace($banned,'',$ftext),' ');
$thirdUrl = $col->find('a',0)->href;
$htmlFa = file_get_html($thirdUrl);
$selectFa = $htmlFa->find('td[width="100%"] table tr');
foreach($selectFa as $deep)
{
$rtext = $deep->plaintext;
$ftext = trim($rtext,' • ');
$info[$a]['city']['university'][$b]['faculty'][$c]['name'] = $tempVar;
$field = extractField($ftext,': ');
if($field)
{
if($field[0]=='website')
{
$info[$a]['city']['university'][$b]['faculty'][$c][$field[0]] = $deep->find('a',0)->href;
}
else
{
$info[$a]['city']['university'][$b]['faculty'][$c][$field[0]] = $field[1];
}
}
$k++;
}
$facName = #$info[$a]['city']['university'][$b]['faculty'][$c]['name'];
$facAddr = #$info[$a]['city']['university'][$b]['faculty'][$c]['address'];
$facPhone = #$info[$a]['city']['university'][$b]['faculty'][$c]['phone'];
$facFax = #$info[$a]['city']['university'][$b]['faculty'][$c]['fax'];
$facEmail = #$info[$a]['city']['university'][$b]['faculty'][$c]['email'];
$facWeb = #$info[$a]['city']['university'][$b]['faculty'][$c]['website'];
$facTax = #$info[$a]['city']['university'][$b]['faculty'][$c]['type'];
echo "<b>ID UNIVERSITATE:</b> ".$a."<br />";
echo "<b>Nume facultate:</b> ".$facName."<br />";
echo "<b>Adresa:</b> ".$facAddr."<br />";
echo "<b>Telefon:</b> ".$facPhone."<br />";
echo "<b>Fax:</b> ".$facFax."<br />";
echo "<b>Email:</b> ".$facEmail."<br />";
echo "<b>Pagina web:</b> ".$facWeb."<br />";
echo "<b>Tip taxa:</b> ".$facTax."<br /><br />";
mysqli_query($conn,"
INSERT INTO faculty
VALUES ('$a','$facName','$facAddr','$facPhone','$facFax','$facEmail','$facWeb','$facTax')
");
$c++;
}
}
$j++;
}
$univCity = #$info[$a]['city']['name'];
$univName = #$info[$a]['city']['university'][$b]['name'];
$univAddr = #$info[$a]['city']['university'][$b]['address'];
$univPhone = #$info[$a]['city']['university'][$b]['phone'];
$univFax = #$info[$a]['city']['university'][$b]['fax'];
$univEmail = #$info[$a]['city']['university'][$b]['email'];
$univWeb = #$info[$a]['city']['university'][$b]['website'];
$univTax = #$info[$a]['city']['university'][$b]['type'];
echo "<b>ID UNIVERSITATE:</b> ".$a."<br />";
echo "<b>Oras:</b> ".$univCity."<br />";
echo "<b>Nume universitate:</b> ".$univName."<br />";
echo "<b>Adresa:</b> ".$univAddr."<br />";
echo "<b>Telefon:</b> ".$univPhone."<br />";
echo "<b>Fax:</b> ".$univFax."<br />";
echo "<b>Email:</b> ".$univEmail."<br />";
echo "<b>Pagina web:</b> ".$univWeb."<br />";
echo "<b>Tip taxa:</b> ".$univTax."<br />";
mysqli_query($conn,"
INSERT INTO university
VALUES ('$a','$univCity','$univName','$univAddr','$univPhone','$univFax','$univEmail','$univWeb','$univTax')
");
$b++;
echo "<br><br>";
}
$a++;
}
}
// SESSION IT, IF THIS JOB IS COMPLETE
if($tmpVar) $_SESSION['LAST'] = $tmpVar;
$i++;
}
print "<h1>".($i-1)."</h1>";
print_r($info);

PHP function display

Hello I have a four computers that I would like to ping before using. The pinging is done via a PHP page with the following function.
if (isset($_POST['playgroundcheck'])) {
function ping($PGIP) {
require_once "Net/Ping.php";
$ping = Net_Ping::factory();
if (PEAR::isError($ping))
echo $ping -> getMessage();
else {
/* Number of packets to send */
$ping -> setArgs(array('count' => 2));
$pgData = $ping -> ping($PGIP);
// print_r($pgData);
if ($pgData -> _received > 0) {
return true;
//echo "<h1><font color=\"green\">ON</font></h1>";
} else {
//echo "<h1><font color=\"red\">OFF</font></h1>";
return false;
}
}
}
$IP2sping = array("pc1" => "192.168.1.121", "pc2" => "192.168.1.122", "pc3" => "192.168.1.123", "pc4" => "192.168.1.124");
foreach ($IP2sping as $key => $value) {
if (ping($value) == true) {
echo $key . " alive<br>";
} else {
echo $key . " off<br>";
}
}
}
I created a form to call the function with a submit button. All of this works but my problems is trying to display the output outside the function. For example currently all output is displayed like the following.
pc1 alive
pc2 alive
pc3 alive
pc4 alive
I want to know how the results of pc1, pc2, pc3 and pc4 can be displayed separately outside the function.
Thanks for answers, but I found a solution that works great for what I want to do using variables variables.
By changing $key to $$key pc1 pc2 pc3 and pc4 become variables and then I can use it anywhere I want.
$IP2sping = array("pc1" => "192.168.1.121",
"pc2" => "192.168.1.122",
"pc3" => "192.168.1.123",
"pc4" => "192.168.1.124");
foreach ($IP2sping as $key => $value){
if (ping($value) == true) {
$key." alive<br>";
} else {
$key." off<br>"; }
}
}
In fact, it's shown outside the function. Here is where you show the results.
if (ping($value) == true) {
echo $key." alive<br>";
} else {
echo $key." off<br>";
}
I would do something like that for what you want:
$available = null;
foreach ($IP2sping as $key => $value){
if (ping($value) == true) {
echo $key." alive<br>";
} else {
echo $key." off<br>";
}
}
Or
$available = null;
foreach ($IP2sping as $key => $value)
$available[$key] = ping($value) ? true : false;
Then, you'll be able to use the $available array for whatever you want :)
Does this help?
if (isset($_POST['playgroundcheck'])) {
// Define the function
function ping($PGIP) {
require_once "Net/Ping.php";
$ping = Net_Ping::factory();
if (PEAR::isError($ping)) {
return FALSE;
} else {
/* Number of packets to send */
$ping->setArgs(array('count' => 2));
$pgData = $ping->ping($PGIP);
// print_r($pgData);
return ($pgData->_received > 0);
}
}
// Define array of items to ping
$IP2sping = array("pc1" => array('ip' => "192.168.1.121"),
"pc2" => array('ip' => "192.168.1.122"),
"pc3" => array('ip' => "192.168.1.123"),
"pc4" => array('ip' => "192.168.1.124")
);
// Get the results of whether the machines are alive
foreach ($IP2sping as $key => $value){
$IP2sping[$key]['alive'] = ping($value);
}
/*
Do a load more stuff
*/
foreach ($IP2sping as $name => $data) {
echo "$name ({$data['ip']}) is ".(($data['alive']) ? 'alive' : 'dead')."<br />\n";
}
}

Categories