If parent slug equals - php

I'm trying to write an if statement where, if a child page's has a slug equal to a specific value, a different statement is echoed. Regardless of the slug value, the function always returns the else value rather than any other.
<?php
global $post;
$post_data = get_post($post->post_parent->post_name);
if ($post_data == 'slug-one'){
$ticket = 'Cats';
} elseif ($post_data == 'slug-two') {
$ticket = 'Dogs';
} else {
$ticket = 'Birds';
}
echo $ticket;
?>
Any ideas as to how I can better write the statement, or what the error occurring is?

As it turns out, I shouldn't have called $post_data = get_post($post->post_parent->post_name). My fixed code is below. Thanks for the advice everyone.
<?php
global $post;
$post_data = get_post($post->post_parent);
if ($post_data->post_name == 'in-the-city'){
$ticket = 'Cats';
} elseif ($post_data->post_name == 'on-the-beach') {
$ticket = 'Dogs';
} else {
$ticket = 'Birds';
}
echo $ticket;
?>

Related

How to fix Array overwritten after foreach loop php

I am having issue data Array overwritten in foreach loop. Result I am getting like this wrongRight together .Right answer is showing but also wrong for example ZucchiniCauliflower.Please help
CODE 1
$data = array();
$dis_07= null;
$dis_03 = null;
if (is_array($row)) {
foreach ($row as $value) {
$gccat_id = $value->gccat_id;
$ccat_id = $value->ccat_id;
$cat = $value->cat_id;
if (isset($gccat_id) && $gccat_id == $id) {
$dis_07 = $value->category;
$dis_02 = $value->child_id;
}
if (isset($ccat_id) && $ccat_id == $id) {
$dis_03 = $value->category;
$dis_02 = $value->parent_id;
}
}
}
$data['Dis_03'] = $dis_03;
$data['Dis_07'] = $dis_07;
if (isset($data['Dis_03'])) {
echo $data['Dis_03'];
}
if (isset($data['Dis_07'])) {
echo $data['Dis_07'];
}
First I tried this way But In one I was getting right in second link I am getting right So Tried the code previous one .In the prvious I am getting correct and wrong one together EExample ZucchiniCauliflower
CODE 2
if (isset($id)) {
$db = Database::newInstance();
$data = array();
$data['cat_status'] = 1;
$sql = "SELECT * FROM category WHERE cat_status=:cat_status ";
$row = $db->read($sql,$data);
$data['id'] = $crypt->decryptId($id);
echo $data['id'];
$id=$data['id'];
if (is_array($row)) {
foreach ($row as $value) {
$gccat_id=$value->gccat_id;
$ccat_id = $value->ccat_id;
$cat = $value->cat_id;
if (isset($gccat_id) && $gccat_id == $id) {
$data['Dis_03']=$value->category;
}
if (isset($ccat_id) && $ccat_id == $id) {
$data['Dis_03'] = $value->category;
break;
}
}
}
}
--------------------------READ FROM HERE------------------------
Here is a link one when I click on this link
$id=$value11->gccat_id;
$title
I expected the output is
Home>Raspberry
Here is a link Second link when I click on this link
Here id is ($value11->gccat_id)
window.open('<?= BASEURL ?>ap/'+id,'_self');
I expected the output is
Home>Cauliflower
1. WHEN I Use the Code 2 (Added break in this condition
(isset($ccat_id) && $ccat_id == $id)) Then click on link second
it gives output Home>Cauliflower which I was expecting. It is
correct.
2. But this time as I added the break in (isset($ccat_id) && $ccat_id == $id). I click on link one It gives wrong output which I was not expecting. Home>Squash which is wrong.
In one link I was expecting
Home>Cauliflower
ERROR NOTE If I add Break; then link Second gives correct output but when I remove Break; then link one give correct. I wanted Both link should give correct output.
Problem was with cat_id,ccat_id ,gccat_id.
I provided 8 digit unique number with the following output,now I am getting the correct output.
function generateUniqueNumber() {
return sprintf('%08d', mt_rand(1, 99999999));
}

If statement never evaluates to true (even when it should)

I'd created an if statement "if ($user_roles == 3) " and this $user_roles has a value of "3" the condition is supposed to be true but the result is always false.
here is my code below:
public function ViewSponsorInfo($sponsor_id)
{
$id = $sponsor_id;
$user_id = User::where('id','=',$id)->get();
$user_roles = [];
foreach ($user_id as $id) {
array_push($user_roles, $id->role);
}/*
dd($user_roles);*/
if ($user_roles == 3) {
$orga = Organization::where('orga_id','=',$sponsor_id)->get();
dd($orga);
return view('pages.Ngo.View-Sponsor-Information',compact('orga'));
}else{
$indi = Individual::where('indi_id','=',$sponsor_id)->get();
dd($indi);
return view('pages.Ngo.View-Sponsor-Information',compact('indi'));
}
}
$user_rolesis not 3 and can never be. it's an array.
its contents, however, can be three.
try:
if(in_array(3, $user_roles)) { ...}
for reference: in_array
$user_roles is an array. So your if statement is always false.
I think, try this one.
foreach ($user_id as $id) {
array_push($user_roles, array('role' => $id->role));
}/*
dd($user_roles);*/
foreach ($user_roles as $user_role) {
if ($user_role['role'] == 3) {
$orga = Organization::where('orga_id','=',$sponsor_id)->get();
dd($orga);
return view('pages.Ngo.View-Sponsor-Information',compact('orga'));
}else{
$indi = Individual::where('indi_id','=',$sponsor_id)->get();
dd($indi);
return view('pages.Ngo.View-Sponsor-Information',compact('indi'));
}
}
or
foreach ($user_id as $id) {
array_push($user_roles, array('role' => $id->role));
}/*
dd($user_roles);*/
foreach ($user_roles as $user_role) {
if ($user_role->role == 3) {
$orga = Organization::where('orga_id','=',$sponsor_id)->get();
dd($orga);
return view('pages.Ngo.View-Sponsor-Information',compact('orga'));
}else{
$indi = Individual::where('indi_id','=',$sponsor_id)->get();
dd($indi);
return view('pages.Ngo.View-Sponsor-Information',compact('indi'));
}
}
Please said something upon it after tried this one.
Judging from what you show your function ViewSponsorInfo() by its very name is only interested in detecting if this user has the sole role '3' in your db.
I mean the outcome is binary isn't it? Either they are a 3 or they are not, no need to go looping thru results.
$user_id = User::where('id','=',$id)->get();
if($user_id[0] !== 3 ) { //***
doSponsorLink();
}else{
doNonSponsorLink();
}
I'm not familiar with Laravel or the db layer your are using, so maybe that is even simply if($user_id).
untested, and here I am assuming user can only have 1 single role, and we do not seem to be making allowances for the user not existing in the db.

Function returns strings but not when stored in variable

I have a strange problem with a function i wrote. When returning an hardcoded string like "Hello" it returns this value, but when i store this value in a variable it doesn't return anything.
Also when i don't store it in a variable and try to return it nothing gets returned.
Below is my code. Can anybody see what i'm doing wrong?
Thanks in advance.
public function getPath($pageID = null) {
if($pageID == null) $pageID = $this->id;
$data = $this->_db->fetch_array("SELECT * FROM `pages` WHERE `id` = '".$pageID."'");
if(!empty($data)) {
$this->tempPath[] = $data['basename'];
if($data['parentID'] != 0) {
$this->getPath($data['parentID']);
} else {
$returnPath = $this->tempPath;
$this->tempPath = array();
$returnPath = implode('/', array_reverse($returnPath));
//This variable holds the value, when echo'ed its the correct value
echo $returnPath;
return $returnPath;
}
}
}
Rewrote the code to the following and now it's working
public function getPath($pageID = null) {
if($pageID == null) $pageID = $this->id;
$data = $this->_db->fetch_array("SELECT * FROM `pages` WHERE `id` = '".$pageID."'");
if(!empty($data)) {
$this->tempPath[] = $data['basename'];
}
return implode('/', $this->tempPath);
}
Problem was that the code was in a foreach loop which kept overwriting the correct values and looping till there is no path to return. Thanks for the suggestions.
More code isn't always better :-)

Won't read variable in function in another script

Whenever I leave my input field empty, $error['commment'] should be set and echoed, but it won't echo, but if I just say echo "some text";, it echo's it.
The comments function is in my functions.php file and $error[] = array() is given in my text.php file above my comments() function, so I don't understand why it's not working, please help guys.
The last bit of PHP code is in a while loop that has to display all the results of my SQL query.
Code above my HTML in text.php:
<?php
session_start();
include("connect.php");
include("functions.php");
$userId = "";
if(isset($_SESSION['loggedIn']) && $_SESSION['loggedIn']){
$userId = $_SESSION['id'];
}
$error[] = array();
comments();
?>
Code in my functions.php:
function comments(){
if (isset($_POST['submit'])) {
$text = $_POST['text'];
$filledIn = true;
if (empty($text)) {
$error['comment'] = "No text filled in";
$filledIn = false;
}
}
}
This is the code in my text.php:
<?php
if(isset($error['comment'])) echo "<p class='error'>".$error['comment']."</p>";
?>
Because $error is not in the scope of the comments() function. So $error['comment'] never gets set.
Ideally you would want to do something like this:
text.php
session_start();
include("connect.php");
include("functions.php");
$userId = "";
if(isset($_SESSION['loggedIn']) && $_SESSION['loggedIn']){
$userId = $_SESSION['id'];
}
$error['comment'] = comments();
functions.php
function comments(){
if (isset($_POST['submit'])) {
$text = $_POST['text'];
if (empty($text)) {
return "No text filled in";
}
}
return null;
}
text.php
<?php
if(!empty($error['comment'])) echo "<p class='error'>".$error['comment']."</p>";
?>
Rather than setting the array key "comments" directly I would use a return value from the comments() function to set it. This allows you to avoid having to use global variables.
Edit: I removed the $filledIn variable from comments() because it wasn't being used in the provided code.
#pu4cu
imo, since you dont come across as very advanced, so that you dont have to make many code changes to what you have now which might get you the minimal edits, and easiest for you to understand;
if in your comment function, you just return a response from this function, like a good little function does, then your response will be available when you call the function, when you set that function to a variable.
//functions.php (note this sets error to true to be failsafe, but this depends on how your using it. set the $response to an empty array in the first line instgad, i.e. array(); if you don't want it failsafe.
<?php
function comments()
{
$response = array(
'error' => TRUE,
'filledIn' => FALSE
);
if (isset($_POST['submit']))
{
$text = $_POST['text'];
$response['filledIn'] = TRUE;
if (empty($text))
{
$response['error']['comment'] = "No text filled in";
}
else{
$response['error'] = NULL;
}
}
return $response;
}
//index.php
session_start();
include("connect.php");
include("functions.php");
$userId = "";
if(isset($_SESSION['loggedIn']) && $_SESSION['loggedIn']){
$userId = $_SESSION['id'];
}
$response = comments();
//text.php
<?php
if($response['error']['comment'])) echo "<p class='error'>".$response['error']['comment']."</p>";
I find your code overly complicated, 3 files, 2 includes, and 1 function, when all you really needed is this:
$error = array();
$error['comment'] = empty($_POST['text']) ? "No text filled in" : $_POST['text'];
echo "<p class='error'>".$error['comment']."</p>";
Your scopes are all mixed up. Your comments() function checks for $_POST, which should be checked before the function is called, and then tries to set a variable within its scope, but you try to access the same variable from outside.
The correct way would be:
text.php:
<?php
session_start();
include("connect.php");
include("functions.php");
$userId = "";
if(isset($_SESSION['loggedIn']) && $_SESSION['loggedIn']){
$userId = $_SESSION['id'];
}
$error[] = array();
if (isset($_POST['submit']) {
comments($_POST);
}
?>
functions.php
function comments($data){
if (isset($data['text'])) {
$text = $data['text'];
if (empty($text)) {
return array('comment' => 'No text filled in');
}
return true;
}
return null;
}
Then you can use the values returned by your function on to act on the result.

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';
}
);

Categories