PHP- How to solve else in nested foreach loop - php

This my code syntax all conditions are working but last else is not working. I found solution in there https://stackoverflow.com/a/5930255/7688968 and I am used break 2 but still not working. How can I solve that?
<?php
$rows = $wpdb->get_results( "SELECT * FROM test WHERE approve_status = '1'" );
if($rowcount>0)
{
foreach ($rows as $row)
{
if ( is_user_logged_in() )
{
echo 'I am user';
$demo = $wpdb->get_results("SELECT * FROM abc WHERE user_mail = '$curentmail'");
foreach($demo as $demos)
{
if(!empty($demos->id)){
echo 'I am IF';
break 2;
}
else{
echo 'I am last ELSE';
}
}
}
else{
echo 'I am guest user';
}
}
}

You are doing the else in the wrong place, it should be done instead of the foreach...
$demo = $wpdb->get_results("SELECT * FROM abc WHERE user_mail = '$curentmail'");
if(!empty($demo)){
foreach($demo as $demos)
{
echo 'I am IF';
}
}
else{
echo 'I am last ELSE';
}
So the logic is that if no records are returned then display your message.

Because the break doesn't break if's. You need to break the foreachs only once, so it's just break;
That else actually doesn't run, because the if is not false. If it uses break in the ifs, else won't run at all. The innermost else runs only, if the very first id of $demos is empty. The second only when if the user is not logged in. These don't relate too much for the foreach cycles.

Move whole foreach block in the function and return from it when needed. For example:
if($rowcount>0)
{
doStuff($rows);
}
function doStuff($rows) {
global $wpdb, $curentmail;
foreach ($rows as $row)
{
if ( is_user_logged_in() )
{
echo 'I am user';
$demo = $wpdb->get_results("SELECT * FROM abc WHERE user_mail = '$curentmail'");
foreach($demo as $demos)
{
if(!empty($demos->id)){
echo 'I am IF';
return;
}
else{
echo 'I am last ELSE';
}
}
}
else{
echo 'I am guest user';
}
}
}

Related

How to check if all rows match a criteria in PHP

I want to check if a certain field of all rows match a criteria.
So if all rows has in the Status field 'RUN' as value then echo "Success".
If there is one row with END as value then echo "Fail":
I'm guessing I need a loop and an IF statement ?
I was thinking something like this but it doesnt return anything:
while($source_row = mysqli_fetch_array($source_selection)){
if ( ($source_row['Stat']) == ("Run" ) {
echo "Success<br />";
} else
echo "Fail";
}
I don't want to echo each row, I want all rows to match a criteria then echo, if one doesn't match a criteria then echo as well.
This should work for you:
First of all you have to fetch all rows with mysqli_fetch_all(). After this I extract only the Stat column with array_column(). Then I just simply array_fill() an array with X values as you have in $states with the value "Run". And check if every value is equals.
$result = mysqli_fetch_all($source_selection, MYSQLI_ASSOC);
$states = array_column($result, "Stat");
if($states == array_fill(0, count($states), "Run")) {
echo "Success";
} else {
echo "Fail";
}
There are some error in the code and you can use the count to match -
$count = 0;
while($source_row = mysqli_fetch_array($source_selection)){
if ($source_row['Stat'] == "Run" ) {
$count++;
}
}
if($count != mysqli_num_rows($source_selection)) {
echo "Fail";
} else echo "Success";
For best performance you can do it directy on the SQL:
select count(*) from table where Stat <> 'Run';
And then test the returning value to check that is greater than zero.
To do it with php you should know that when you find an error you can stop the iterations. The code would look like that:
while($source_row = mysqli_fetch_array($source_selection)){
if ( $source_row['Stat'] != "Run" ){
$fail = true;
break;
}
}
if ($fail) {
echo "Fail";
} else
echo "Success";
}
Try this
$success=true;
while($source_row = mysqli_fetch_array($source_selection)){
if ( ($source_row['Stat']) != ("Run" ) {
$success=false;
}
}
if ($success) {
echo "Success";
} else {
echo "Fail";
}

Variables as variables from MySQL result

I have a MySQL database table, where are configured all needed colors in hexadecimal, rgb decimal and cmyk color models. All I wanna do is storing all suitable results according to the query to variables. Please show newbie how can he do that right and effectively... Thanks in advance
DB
My disgrace
$result=$mysqli->query("SELECT * FROM config_colors WHERE `color_model_type`='hex' OR `color_model_type`='rgb'" );
while ($row=mysqli_fetch_array($result)) {
if (($row['color']==='white') || ($row['color']==='black')) {
if ($row['color_model_type']==='hex') {
print_r ('$c_h_'.$row['color'].' = '.$row['color_value']);
}
else if ($row['color_model_type']==='rgb') {
print_r ('$c_r_'.$row['color'].' = '.$row['color_value']);
}
else {}
}
else {
if ($row['color_model_type']==='hex') {
if ($row['monochromatic_level']==='lightest') {
print_r ('$c_h_lt_'.$row['color'].' = '.$row['color_value']);
}
else if ($row['monochromatic_level']==='lighter') {
print_r ('$c_h_lr_'.$row['color'].' = '.$row['color_value']);
}
else if ($row['monochromatic_level']==='light') {
print_r ('$c_h_l_'.$row['color'].' = '.$row['color_value']);
}
else if ($row['monochromatic_level']==='medium') {
print_r ('$c_h_m_'.$row['color'].' = '.$row['color_value']);
}
else if ($row['monochromatic_level']==='dark') {
print_r ('$c_h_d_'.$row['color'].' = '.$row['color_value']);
}
else if ($row['monochromatic_level']==='darker') {
print_r ('$c_h_dr_'.$row['color'].' = '.$row['color_value']);
}
else if ($row['monochromatic_level']==='darkest') {
print_r ('$c_h_dt_'.$row['color'].' = '.$row['color_value']);
}
else {}
}
else if ($row['color_model_type']==='rgb') {
if ($row['monochromatic_level']==='lightest') {
print_r ('$c_r_lt_'.$row['color'].' = '.$row['color_value']);
}
else if ($row['monochromatic_level']==='lighter') {
print_r ('$c_r_lr_'.$row['color'].' = '.$row['color_value']);
}
else if ($row['monochromatic_level']==='light') {
print_r ('$c_r_l_'.$row['color'].' = '.$row['color_value']);
}
else if ($row['monochromatic_level']==='medium') {
print_r ('$c_r_m_'.$row['color'].' = '.$row['color_value']);
}
else if ($row['monochromatic_level']==='dark') {
print_r ('$c_r_d_'.$row['color'].' = '.$row['color_value']);
}
else if ($row['monochromatic_level']==='darker') {
print_r ('$c_r_dr_'.$row['color'].' = '.$row['color_value']);
}
else if ($row['monochromatic_level']==='darkest') {
print_r ('$c_r_dt_'.$row['color'].' = '.$row['color_value']);
}
else {}
}
else {}
}
}
Additional questions about query: Is query written in terms of safety against SQL injection? What if my WHERE clause contains an integer?
You can use variable variables to dynamically assign values to new variables
instead of
print_r ('$c_h_'.$row['color'].' = '.$row['color_value']);
try
$var = 'c_h_'.$row['color'];
$$var = $row['color_value'];
Your query is safe on SQL injection as it does not receive any input data. There is no entry point for injection while you keep the query as it is.
About your problem and if I understood it, you're better going with an array per color type.
<?php
$rgb = array();
$hex = array();
$result = mysqli->query("
SELECT
*
FROM config_colors
WHERE
`color_model_type`='hex' OR
`color_model_type`='rgb'
");
while ($row = mysqli_fetch_array($result))
{
if ($row['color_model_type']==='hex')
$hex[ $row['color'] ] = $row;
elseif ($row['color_model_type']==='rgb')
$rgb[ $row['color'] ] = $row;
}
Later if you need information about white color in rgb format you just have to do var_dump($rgb['white']);

Checking for undefined variables in a function php

So I've been trying to devise a function that will echo a session variable only if it is set, so that it wont create the 'Notice' about an undefined variable. I am aware that one could use:
if(isset($_SESSION['i'])){ echo $_SESSION['i'];}
But it starts to get a bit messy when there are loads (As you may have guessed, it's for bringing data back into a form ... For whatever reason). Some of my values are also only required to be echoed back if it equals something, echo something else which makes it even more messy:
if(isset($_SESSION['i'])){if($_SESSION['i']=='value'){ echo 'Something';}}
So to try and be lazy, and tidy things up, I have tried making these functions:
function ifsetecho($variable) {
if(!empty($variable)) {
echo $variable;
}
}
function ifseteqecho($variable,$eq,$output) {
if(isset($variable)) {
if($variable==$eq) {
echo $output;
}
}
}
Which wont work, because for it to go through the function, the variable has to be declared ...
Has anyone found a way to make something similar to this work?
maybe you can achieve this with a foreach?
foreach ($_SESSION as $variable)
{function ifseteqecho($variable,$eq,$output) {
if($variable==$eq) {
echo $output;
}
else echo $variable;
}
}
now this will all check for the same $eq, but with an array of corresponding $eq to $variables:
$equiv = array
('1'=>'foo',
'blue'=>'bar',);
you can check them all:
foreach ($_SESSION as $variable)
{function ifseteqecho($variable,$equiv) {
if(isset($equiv[$variable])) {
echo $equiv[$variable];
}
else {
echo $variable;
}
}
}
Something like this?, you could extend it to fit your precise needs...
function echoIfSet($varName, array $fromArray=null){
if(isset($fromArray)){
if(isset($fromArray[$varName])&&!empty($fromArray[$varName])){
echo $fromArray[$varName];
}
}elseif(isset($$varName)&&!empty($$varName)){
echo $$varName;
}
}
You may use variable variables:
$cat = "beautiful";
$dog = "lovely";
function ifsetecho($variable) {
global $$variable;
if(!empty($$variable)){
echo $$variable;
}
}
ifsetecho("cat");
echo "<br/>";
ifsetecho("dog");
echo "<br/>";
ifsetecho("elephant");
UPDATE: With a rather complex code I’ve managed to meet your requirements:
session_start();
$cat = "beautiful";
$dog = "lovely";
$_SESSION['person']['fname'] = "Irene";
function ifsetecho($variable){
$pattern = "/([_a-zA-Z][_a-zA-Z0-9]+)".str_repeat("(?:\\['([_a-zA-Z0-9]+)'\\])?", 6)."/";
if(preg_match($pattern, $variable, $matches)){
global ${$matches[1]};
if(empty(${$matches[1]})){
return false;
}
$plush = ${$matches[1]};
for($i = 2; $i < sizeof($matches); $i++){
if(empty($plush[$matches[$i]])){
return false;
}
$plush = $plush[$matches[$i]];
}
echo $plush;
return true;
}
return false;
}
ifsetecho("cat");
echo "<br/>";
ifsetecho("dog");
echo "<br/>";
ifsetecho("elephant");
echo "<br/>";
ifsetecho("_SESSION['person']['fname']");
echo "<br/>";
ifsetecho("_SESSION['person']['uname']");
echo "<br/>";

php for loop: error message if condition not met

My foreach loop:
$empty = "You cannot decommission this truck. It is in use."
$msg = "";
foreach ($trucks_to_remove as $truck_id) {
$truck_id = trim($truck_id);
if (strlen($truck_id)) {
$msg .= decom_truck(
$db,
$depot_id,
$truck_id
);
}
else
{
echo $empty;
}
}
echo $msg;
If the condition is not met, it means the sql cursor that preceded this foreach loop did not return a result for this truck_id (meaning it is in use), I just want a simple message sent to the page to alert the user.
It does not have to be a pop-up or the like. Where would I put my write or print statement? I assume I'd use an else clause but when I add an else inside the foreach loop (see above), I get nothing printed to the page. I have also tried the following:
else if (strlen($truck_id)) == 0
{
echo $empty;
}
I am very new to php.
$arr1 = array();
if(!$arr1)
{
echo 'arr1 is emty<br/>';
$arr2 = array(1, 2);
if($arr2)
echo 'arr2 has data';
exit();
}

Generating XML file through PHP results in a minor issue . Please help

In order to generate a XML i am using following Code currently.
.<?php
require ('../dbconfig/dbconfig.php');
$appId = $_GET['id'];
$sqlTabs = "Select _id,tab_title,position from tab_info where app_id=$appId order by position ";
$resultTabs=mysql_query($sqlTabs );
$countTabs=mysql_num_rows($resultTabs);
if($countTabs>0)
{
echo '<application applicationName="sample app">';
echo '<tabs>';
while ($rowTab = mysql_fetch_array($resultTabs) ) {
echo '<tab id="t'.$rowTab['_id'].'" tabtitle="'.$rowTab['tab_title'].'" position="'.$rowTab['position'].'" data="somedata">';
$sqlTabItems = "Select _id as tabitemId,item_type,item_title,item_data from items_info where tab_id=".$rowTab['_id']." and parent_id=0 order by _id ";
$resultTabItems=mysql_query($sqlTabItems);
$countTabItems=mysql_num_rows($resultTabItems);
if($countTabItems>0)
{
$level = 1;
echo '<listItems>';
while ($rowTabItem = mysql_fetch_array($resultTabItems) ) {
echo '<listItem id="'.$rowTabItem['tabitemId'].'" parentId="t'.$rowTab['_id'].'" itemtype="'.$rowTabItem['item_type'].'" itemtitle="'.$rowTabItem['item_title'].'" itemdata="'.$rowTabItem['item_data'].'" level="'.$level.'">';
giveitems($rowTabItem['tabitemId'],$rowTab['_id'],$level);
echo '</listItem>';
}
echo '</listItems>';
}
else
echo 'No Data';
echo '</tab>';
}
echo '</tabs></application>';
}
else
{
echo 'No Data';// no tabs found
}
function giveitems($pitemId,$tabId,$level)
{
$sqlItems = "Select _id,item_type,item_title,item_data from items_info where parent_id=".$pitemId." order by _id ";
$resultItems=mysql_query($sqlItems);
$countItems=mysql_num_rows($resultItems);
$numbers = 0;
if($countItems>0)
{
$level = $level +1;
echo '<listItems>';
while ($rowItem = mysql_fetch_array($resultItems) ) {
echo '<listItem id="'.$rowItem[0].'" parentId="'.$pitemId.'" itemtype="'.$rowItem[1].'" itemtitle="'.$rowItem[2].'" itemdata="'.$rowItem[3].'" level="'.$level.'">';
/*********** Recursive Logic ************/
if(giveitems($rowItem[0],$tabId,$level)==1)
{
echo '</listItem></listItems>';
return 1;
}
else
{
echo '</listItem></listItems>';
return -1;
}
}
}
else
{
echo 'No Data';// no tabs found
return -1;
}
}
?>
Now in this code i want to replace all echo statements with a String variable and then i want to write that String variable content into a file , the porblem is if i define the string variable at the top of the file even then also that string variable cannot accessible from the giveItems functions below.
Pls suggest some solution
To access a global variable from within a function you need to write global $varname; at the top of that function's definition. Example:
function giveitems($pitemId,$tabId,$level) {
global $xmlstring;
// ....
}
However, this is pretty bad practice nowadays and you'd be better off writing a class that will both produce the XML and write it to a file.

Categories