how to access function variable outside if statement php - php

How can i access function variable out side if else statement as you can see when i declared opType == "Anand" than code will run but i use post man to saw result
if (!(empty($_POST)) & isset($_POST)) {
$opType = $_POST["opType"];
if ($opType == "insertFuelEngineMap") {
//insert into fuel_engine_capacity_mapping setValuesForCreation(false);
$query = "INSERT INTO fuel_engine_capacity_mapping(cf_mapping_id,capacity_id) VALUES ('$cf_mapping_id','$capacity_id')";
$loginResult = mysqli_query($link, $query);
if (mysqli_affected_rows($link) > 0) {
$userdata = array('status' => '200', 'msg' => "insertlol into fuel_engine_capacity_mapping successfully", 'mapping_id' => $link->insert_id);
} else {
$userdata = array('status' => '404', 'msg' => " Cant fuel_engine_capacity_mapping " . mysqli_error($link));
}
}
if ($opType == "anand") {
function addition() {
$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}
}
}
addition();
echo $z;

You can return the value :
//Modify you function so it will return the result
function addition() {
return $GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}
Then :
//Catch variable and echo
echo $z = addition();
I hope it's what you want, because your question is not clear.
Moreover, you 'll have error if $opType is different than anand because function 'll be called but it 'll not exist.
It should be better to declare it in any case and not only if $opType === 'anand'.

Declaring a function inside and if statement, only if some variable is set and then calling it outside that if statement where you do not check that that variable is set a plan for disaster!
Instead define the function in the main body of the code and call it with parameters, and just return the computed value
<?php
function addition($a, $b) {
return $a + $b;
}
$z = addition($x, $y);
echo $z;

Related

php Function echo's wrong string

I'm fairly new to PHP so forgive me if this function is badly done.
I have a function:
function socialLink($sm_type = NULL) {
if ($sm_type = 'twitter') {
echo 'https://www.twitter.com';
} else {
echo 'https://www.facebook.com';
}
}
In my code when I call the function socialLink('facebook'); it echo's the Twitter URL.
Surely it should echo the Facebook URL since $sm_type would be equal to 'facebook' not twitter ?
Any help would be appreciated.
Set your if condition with this,
function socialLink($sm_type = NULL) {
if ($sm_type == 'twitter') {
echo 'https://www.twitter.com';
} else {
echo 'https://www.facebook.com';
}
}
See this.
function socialLink($sm_type = NULL) {
if ($sm_type == 'twitter') {
echo 'https://www.twitter.com';
} else {
echo 'https://www.facebook.com';
}
}
NOTE: Single = use to assign the value and = = use to compare values
Different's Between = , = = , = = =
= operator Used to just assign the value.
= = operator Used to just compares the values not datatype
= = = operator Used to Compare the values as well as datatype.
Your if statement does not use a comparison operator, it is an assignment (=). For a comparison, please use "==".
if ($sm_type == 'twitter') {
echo 'https://www.twitter.com';
} else {
echo 'https://www.facebook.com';
}
if ($sm_type == 'twitter') {
echo 'https://www.twitter.com';
} else {
echo 'https://www.facebook.com';
}
In php == is use for string comparison so, In this case you can't used = for that, simple :)

Is there any possibility to break a loop while calling a function?

Let's say I have a simple code:
while(1) {
myend();
}
function myend() {
echo rand(0,10);
echo "<br>";
if(rand(0,10) < 3) break;
}
This will not work with error code 'Fatal error: Cannot break/continue 1 level on line'.
So is there any possibility to terminate the loop during a subfunctin execution?
Make the loop condition depend upon the return value of the function:
$continue = true;
while( $continue) {
$continue = myend();
}
Then, change your function to be something like:
function myend() {
echo rand(0,10);
echo "<br>";
return (rand(0,10) < 3) ? false : true;
}
There isn't. Not should there be; if your function is called somewhere where you're not in a loop, your code will stop dead. In the example above, your calling code should check the return of the function and then decide whether to stop looping itself. For example:
while(1) {
if (myend())
break;
}
function myend() {
echo rand(0,10);
echo "<br>";
return rand(0,10) < 3;
}
Use:
$cond = true;
while($cond) {
$cond = myend();
}
function myend() {
echo rand(0,10);
echo "<br>";
if(rand(0,10) < 3) return false;
}

PHP - putting if statement coding inside of a variable

I am trying to get an if statement to dynamically code itself based on user input. So the if statement code is being inserted into a variable ($if_statement_variable), like this:
$if_statement_variable = "if (";
$price = trim($_GET["Price"]);
if (!empty($price)) {
$if_statement_variable .= " $Product->price < $price ";
}
$product_name = trim($_GET["Product_name"]);
if (!empty($product_name)) {
$if_statement_variable .= " && $Product->$product_name == 'product_name_string' ";
}
// plus many more if GET requests
$if_statement_variable .= ") ";
Then results from an XML file will be displayed based on user values submitted and the $if_statement_variable.
$XMLproducts = simplexml_load_file("products.xml");
foreach($XMLproducts->product as $Product) {
echo $if_statement_variable; // Here is where the problem is
{ // opening bracket for $variable_if_statement
echo $Product->$product_name; // products displayed based on if statement code in $if_statement_variable
} //closing bracket for $variable_if_statement
}
The echo $if_statement_variable above correctly displays $price from this variable string, but does NOT display $Product->price. Assuming $price had a value of 1000, the output is if ( == 1000 ). How can I get $Product->price to correctly insert itself into the $if_statement_variable so that it displays the $Product->price values from the XML file?
If you're trying to generate a boolean value dynamically, based on some complicated logic, just assign the true/false value to a variable, (say, $booleanValue) and then do if($booleanValue){}
Something like:
$price = trim($_GET['price']);
$product_name = trim($_GET['Product_name']);
if(!empty($price)){
$booleanValue = ($Product->price < $price);
}
if(!empty($productName)){
$booleanValue = ($booleanValue && $Product->$product_name == 'product_name_string')
}
if($booleanValue){
echo $Product->$product_name;
}
In other words, create a variable to hold the actual boolean value, not a string to hold an expression that will evaluate to a boolean value.
Do not build PHP source as a string. In this case callables are a better solution. A callable is a function inside a variable. In PHP this might be an function name, and array with an object and a method name, an anonymous function or an object implementing invoke.
Here is an example for anonymous functions:
function getCondition($parameters) {
$conditions = [];
if (isset($parameters['Price']) && trim($parameters['Price']) != '') {
$price = trim($parameters['price']);
$conditions[] = function($product) use ($price) {
return $product->price < $price;
}
}
if (isset($parameters['Product_name']) && trim($parameters['Product_name']) != '') {
$productName = trim($parameters['Product_name']);
$conditions[] = function($product) use ($productName) {
return $product->product_name == $productName;
}
}
return function($product) use ($conditions) {
foreach ($conditions as $condition) {
if (!$condition($product)) {
return FALSE;
}
}
return TRUE;
}
}
$condition = getConditon($_GET);
if ($condition($product)) {
...
}
It is important that each function can be called the same way. So if you call the condition function you not need to know, which condition it is. In the example above you can imagine that the getCondition() function can get really complex really fast if you add additional conditions.
If you encapsulate the conditions into classes, the usage becomes more readable:
$condition = new \YourCompany\Product\Conditions\Group(
new \YourCompany\Product\Conditions\PriceMaximum($_GET, 'Price'),
new \YourCompany\Product\Conditions\Name($_GET, 'Product_name')
);
if ($condition($product)) {
...
}
This way you separate the actual condition logic from the from the use. The source of all classes is some more then the anonymous function variant. But you you can put each class in it's own file and use them in any combination you need.
The classes need to implement __invoke().
class Group {
private $_conditions = array();
public function __construct() {
$this->_conditions = func_get_args();
}
public function __invoke($product) {
foreach ($this->_conditions as $condition) {
if (!$condition($product)) {
return FALSE;
}
}
return TRUE;
}
}
class Name {
private $_productName = NULL;
public function __construct($parameters, $name) {
if (isset($parameters[$name]) && trim($parameters[$name]) > 0) {
$this->_productName = trim($parameters[$name]);
}
}
public function __invoke($product) {
return (
NULL === $this->_productName ||
$product->product_name == $this->_productName
);
}
}
class PriceMaximum {
private $_maximum = NULL;
public function __construct($parameters, $name) {
if (isset($parameters[$name]) && trim($parameters[$name]) > 0) {
$this->_maximum = trim($parameters[$name]);
}
}
public function __invoke($product) {
return (
NULL === $this->_maximum ||
$product->price < $this->_maximum
);
}
}
This concept can even be used together with an anonymous function:
$condition = new \YourCompany\Product\Conditions\Group(
new \YourCompany\Product\Conditions\PriceMaximum($_GET, 'Price'),
new \YourCompany\Product\Conditions\Name($_GET, 'Product_name'),
function ($product) {
return $product->category == 'food';
}
);

call to undefined function msg()

i m getting an error in the php code..
Fatal error: Call to undefined function msg()
but the function is already defined in the code here
whenever i click on a login button this login script runs
<?php
mysql_select_db("elunika", $con);
$a = $_POST['em'];
$b = $_POST['pwd'];
$c = $_POST['log'];
$b = md5($b);
if (isset($c)) {
$q = mysql_query("select * from registeration where email='$a' and password='$b'");
$r = mysql_num_rows($q);
if ($r) {
$_SESSION["Authenticated"] = 1;
$_SESSION['id'] = $a;
}
else {
$_SESSION["Authenticated"] = 0;
}
if ($_SESSION["Authenticated"] === 0) {
die(msg(0, "Incorrect Information"));
}
else {
session_write_close();
echo msg(1, "profile.php");
}
function msg($status, $txt)
{
return '{"status":' . $status . ',"txt":"' . $txt . '"}';
}
}
?>
Only unscoped functions are defined at compile-time (prior to execution). Your msg function however is just going to be defined if the if branch (the if (isset(…)) on line 9) is entered; so it's only going to be defined at the moment where the executor reaches it.
But in your code msg() is already called before the function declaration was encountered at run-time. Moving the function declaration up (= before the msg() call) should help:
function msg ($status, $txt) {
return '{"status":'.$status.',"txt":"'.$txt.'"}';
}
if($_SESSION["Authenticated"] === 0) {
die(msg(0,"Incorrect Information"));
} else {
session_write_close();
echo msg(1,"profile.php");
}

PHP function not being called, am i missing something obvious?

i think i need a second pair of eyes.
I have some ajax calling a php file, and it's returning json. This all works fine. I'm then alerting the data elements i return for testing purposes. In doing this i narrowed down my function is not being called.
<?php
// database functions
$response = array();
$count = 1;
// connect to db
function connect() {
$response['alert'] = 'connect ran'; // does not get alerted
}
// loop through query string
foreach ($_POST as $key => $value) {
switch ($key) {
case 'connect':
$response['alert'] = 'case ran';
if ($value == 'true') {
$response['alert'] = 'if ran'; // this is what gets alerted, should be overwriten by 'connect ran'
connect(); // function call does not work?
} else {
$response['alert'] = 'false';
$mysqli->close();
}
break;
case 'otherstuff':
break;
}
++$count;
}
$response['count'] = $count;
echo json_encode($response);
?>
Any ideas? Thanks.
your $response variable is out of scope.. use global keyword inside your function to registering your outer variable(s)
function connect() {
global $response;
$response['alert'] = 'connect ran';
}
or SDC's edit:
function connect($response) {
$response['alert'] = 'connect ran';
}
connect($response);
actually you defined the result variable but in another type and you also have another result variable at the top so you put data in $result[] but you try to use $result so your code may not give you the expected result.

Categories