Exclude value from foreach loop output - php

I am looking to exclude a specific value from my foreach output where it occurs in either friend_one or friend_two. I do not want to exclude this from my query.
The parameter to exclude would be $profile_user where it occurs in either friend_one or friend_two. I tried to do this if(in_array($friend_total_row->friend_one == $profile_user)), but I am getting errors with it, plus it only has friend_one in it.
Anyone have an idea how I can do this?
<?php
//Friends --- total
$friend_status = 2;
$friend_sql = "
SELECT *
FROM friends
WHERE (friend_one = :profile_user or friend_two = :profile_user)
AND status = :total_status
";
$friend_stmt = $con->prepare($friend_sql);
$friend_stmt->execute(array(':profile_user' => $profile_user, ':total_status' => $friend_status));
$friend_total_rows = $friend_stmt->fetchAll(PDO::FETCH_ASSOC);
$count_total_friend = $friend_stmt->rowCount();
?>
<div id="friend-list-container">
<div id="friend-list-count">Friends <span class="light-gray"><?php echo $count_total_friend; ?></span></div>
<div id="friend-list-image-container">
<?php
foreach ($friend_total_rows as $friend_total_row) {
if(in_array($friend_total_row->friend_one == $profile_user)) {
continue;
}
else {
$friend_1 = $friend_total_row['friend_one'];
$friend_2 = $friend_total_row['friend_two'];
//$friend_status = $friend_total_row['status'];
//$friend_status_date = $friend_total_row['date'];
}
echo $friend_1 . $friend_2;
}
?>
I am only wanting to exclude the $profile_user from outputting, which is where the X is. Then I want the squared output to show.

Updated answer :
foreach ($friend_total_rows as $friend_total_row) {
$friend_1 = $friend_total_row['friend_one'];
$friend_2 = $friend_total_row['friend_two'];
if($friend_1 !== $profile_user) {
echo $friend_1;
}
if($friend_2 !== $profile_user) {
echo $friend_2;
}
}

Related

Query Join table to sort by menudindex

Here is my query:
$results = $modx->query("SELECT contentid FROM modx_site_tmplvar_contentvalues WHERE tmplvarid=107");
I need to sort it by menuindex so i tried this:
$results = $modx->query("SELECT contentid FROM modx_site_tmplvar_contentvalues JOIN modResource WHERE tmplvarid=107 ORDER BY menuindex DESC");
I'm not familiar at all whith this. Of course it doesn't work. Someone told me to use XPDO but i know nothing about it. Do i miss something? What should i do to make it work ?
Here is the full code :
<?php
$results = $modx->query("SELECT contentid FROM modx_site_tmplvar_contentvalues WHERE tmplvarid=107");
// description tv: 108
// vignette tv: 121
if (!is_object($results)) {
return;
}
$breves = array();
while($r = $results->fetch(PDO::FETCH_COLUMN, 0)){
$breves[] = $r;
}
$queryIn = implode(',' , $breves);
$results_2 = $modx->query("SELECT contentid, tmplvarid, value FROM modx_site_tmplvar_contentvalues WHERE contentid IN ({$queryIn}) AND tmplvarid IN (108, 121)");
if (!is_object($results_2)) {
return;
}
$tvValues = array();
while($v = $results_2->fetch(PDO::FETCH_ASSOC)){
if($v['tmplvarid'] == 108){
$tvValues[$v['contentid']]['desc'] = $v['value'];
} else {
$tvValues[$v['contentid']]['vignette'] = $v['value'];
}
}
$output = "";
foreach ($breves as $res_id) {
$page = $modx->getObject('modResource', $res_id);
$alias = $page->get('alias');
$id = $page->get('id');
$page_title = $page->get('pagetitle');
$description = $tvValues[$res_id]['desc'];
if(!$description || $description == ""){
$description = $page->get('content');
}
$description = strip_tags($description);
$description = mb_strimwidth($description, 0, 150, "...");
$vignette = $tvValues[$res_id]['vignette'];
if($vignette){
$vignette = "/assets/upload/pln/" . $vignette;
} else {
$vignette = "https://www.commune-ploudaniel.fr/assets/templates/pln/default-b7824fcd998f51baf0f0af359a72e760.png";
}
$output .= <<<HTML
<div class="xpro-slider-item">
<div class="xp-news-classic-block">
<div class="xp-hover-image">
</div>
<a class="xp-view-lightbox" href="{$alias}.html" ><i class="fa fa-plus"></i></a>
<img src="{$vignette}" alt="{$alias}" style="width:375px; height:270px; object-fit: cover;"/>
</div>
<div class="xp-news-detail">
<h4>{$id}{$page_title}</h4>
<p>{$description}</p>
<div class='xp-news-footer'></div>
</div>
</div>
</div>
HTML;
$output .= PHP_EOL;
}
return $output;
Try this for MODX:
$q = $modx->newQuery('modTemplateVarResource');
$q->leftJoin('modResource', 'mr', 'mr.id = modTemplateVarResource.contentid');
$q->where(array(
'modTemplateVarResource.tmplvarid' => 107
));
$q->select(array(
'modTemplateVarResource.contentid'
));
$q->sortby('modResource.menuindex', 'DESC');
$q->prepare();
$q->stmt->execute();
$result = $q->stmt->fetch(PDO::FETCH_ASSOC);
print_r($result);

Select where to display values from MySQL DB in CodeIgniter

I want to display the values from MySQL database using CodeIgniter. Here, I am using SELECT to query to compare the multiple values using the WHERE condition.
I want to display the checked rows values from one page to another. I am passing the the checked value via URL. In the second page, I am getting the value from the URL, and using the explode() function to split the value and display using a for loop. Here, values are displaying correctly. But, when passing the array values to the SELECT query, it displays only the last rows.
I want to display all checked rows from the database.
For example, sample code:
<?php
$id = $this->uri->segment(4);
$arr = explode(',', $id);
for ($kk = 0; $kk < count($arr); $kk++) {
echo $id_val13 = $arr[$kk];
$basicUrl = $this->config->item("basicUrl");
$basicUrl['bread_crumb'] = $this->breadcrumb();
$query = $this->db->query("SELECT aa.id as id,customer_type_id,start_time,close_time,dd.name as customer_name,bb.name as vehicle_name,cc.name as driver_name,other_expensive,depature_city,destination_city,journey_status,payment,tour_file,DATE_FORMAT(aa.created_date, '%d/%m/%Y') as created_date FROM " . $this->tbl . " as aa
left join vehicle as bb on aa.vehicle_id=bb.id
left join driver as cc on aa.driver_id=cc.id
left join tbl_customer as dd on aa.customer_id=dd.id
WHERE aa.id = $id_val13");
$result = array();
if ($query->num_rows()) {
$i = 1;
foreach ($query->result() as $row) {
$result_row = array();
$result_row[] = '<input type="checkbox" name="chk_id" id="chk_id" value="' . $row->id . '" />';
$result_row[] = $row->id;
$result_row[] = $row->customer_name;
if ($row->customer_type_id == "1")
$result_row[] = "Tour";
else if ($row->customer_type_id == "2")
$result_row[] = "Company";
else if ($row->customer_type_id == "3")
$result_row[] = "Guest";
$result_row[] = $row->driver_name;
$result_row[] = $row->vehicle_name;
$result_row[] = $row->destination_city;
$result_row[] = $row->start_time;
$result_row[] = $row->close_time;
$result_row[] = $row->payment;
$result_row[] = $row->other_expensive;
$result_row[] = $row->journey_status == "1" ? "Complete" : "On Progress";
if ($row->tour_file != "") {
$result_row[] = '' . $row->tour_file . '';
} else {
$result_row[] = "No File";
}
$result_row[] = $row->created_date;
$action_btn = action_button("Edit", $row->id) . action_button("Delete", $row->id) . action_button("Select", $row->id);
$result_row[] = $action_btn;
$result[] = $result_row;
$i++;
}
}
}
$tbl_header = array(
"",
"S NO",
"Customer Name",
"Type",
"Driver Name",
'Vehicle Name',
"Destination City",
"Start Time",
"Close Time",
"Rupee",
"Other Expensive",
"Journey Status",
"Itinerary",
"Created Date",
array(
"Edit",
"Delete"
)
);
$basicUrl['table'] = $this->makeTable($result, $tbl_header, $bool = TRUE);
$this->parser->parse("admin/center", $basicUrl);
?>
For example:
$array = array("1","2","6");
Normally using explode() and for loop, it display all the values. When I use select query using CodeIgniter, it displays the last row only.
Try this (I have defined $result before for loop) Also this is not a good practice to use your code like this use controller and models to do all the logical and database work....
<?php
$id = $this->uri->segment(4);
$arr = explode(',', $id);
$result=array();
for ($kk = 0; $kk < count($arr); $kk++)
{
echo $id_val13 = $arr[$kk];
$basicUrl = $this->config->item("basicUrl");
$basicUrl['bread_crumb'] = $this->breadcrumb();
$query=$this->db->query("SELECT aa.id as id,customer_type_id,start_time,close_time,dd.name as customer_name,bb.name as vehicle_name,cc.name as driver_name,other_expensive,depature_city,destination_city,journey_status,payment,tour_file,DATE_FORMAT(aa.created_date, '%d/%m/%Y') as created_date FROM ".$this->tbl." as aa
left join vehicle as bb on aa.vehicle_id=bb.id
left join driver as cc on aa.driver_id=cc.id
left join tbl_customer as dd on aa.customer_id=dd.id
WHERE aa.id = $id_val13");
if($query->num_rows()){
$i=1;
foreach($query->result() as $row){
$result_row=array();
$result_row[]='<input type="checkbox" name="chk_id" id="chk_id" value="'.$row->id.'" />';
$result_row[]=$row->id;
$result_row[]=$row->customer_name;
if($row->customer_type_id=="1")
$result_row[]="Tour";
else if($row->customer_type_id=="2")
$result_row[]="Company";
else if($row->customer_type_id=="3")
$result_row[]="Guest";
$result_row[]=$row->driver_name;
$result_row[]=$row->vehicle_name;
$result_row[]=$row->destination_city;
$result_row[]=$row->start_time;
$result_row[]=$row->close_time;
$result_row[]=$row->payment;
$result_row[]=$row->other_expensive;
$result_row[]=$row->journey_status=="1" ? "Complete" : "On Progress";
if($row->tour_file!="")
{
$result_row[]=''.$row->tour_file.'';
}
else
{
$result_row[]="No File";
}
$result_row[]=$row->created_date;
$action_btn=action_button("Edit",$row->id).action_button("Delete",$row->id).action_button("Select",$row->id);
$result_row[]=$action_btn;
$result[]=$result_row;
$i++;
}
}
}
$tbl_header=array("","S NO","Customer Name","Type","Driver Name",'Vehicle Name',"Destination City","Start Time","Close Time","Rupee","Other Expensive","Journey Status","Itinerary","Created Date",array("Edit","Delete"));
$basicUrl['table']=$this->makeTable($result,$tbl_header,$bool=TRUE);
$this->parser->parse("admin/center",$basicUrl);
?>

A Mysql Query from joomla is taking very long time

Sorry for this Question. I am not a Good Programmer
Everything Executed well with few menu items. but with 14K menu items. i stuck with this query. This is happening when i try to access
administrator/index.php?option=com_modules&view=module&layout=edit&id=97
Is there any way to alter the query ??
Query
SELECT a.id AS value,
a.title AS text,
a.alias,
a.level,
a.menutype,
a.type,
a.template_style_id,
a.checked_out
FROM gjb0e_menu AS a
LEFT JOIN `gjb0e_menu` AS b
ON a.lft > b.lft
AND a.rgt < b.rgt
WHERE a.published != -2
GROUP BY a.id,
a.title,
a.alias,
a.level,
a.menutype,
a.type,
a.template_style_id,
a.checked_out,
a.lft
ORDER BY a.lft ASC
Php code
require_once JPATH_ADMINISTRATOR . '/components/com_menus/helpers/menus.php';
$menuTypes = MenusHelper::getMenuLinks();
<ul class="treeselect">
<?php foreach ($menuTypes as &$type) : ?>
<?php if (count($type->links)) : ?>
<?php $prevlevel = 0; ?>
<li>
<div class="treeselect-item pull-left">
<label class="pull-left nav-header"><?php echo $type->title; ?></label></div>
<?php foreach ($type->links as $i => $link) : ?>
<?php
if ($prevlevel < $link->level)
{
echo '<ul class="treeselect-sub">';
} elseif ($prevlevel > $link->level)
{
echo str_repeat('</li></ul>', $prevlevel - $link->level);
} else {
echo '</li>';
}
$selected = 0;
if ($this->item->assignment == 0)
{
$selected = 1;
} elseif ($this->item->assignment < 0)
{
$selected = in_array(-$link->value, $this->item->assigned);
} elseif ($this->item->assignment > 0)
{
$selected = in_array($link->value, $this->item->assigned);
}
?>
<li>
<div class="treeselect-item pull-left">
<input type="checkbox" class="pull-left" name="jform[assigned][]" id="<?php echo $id . $link->value; ?>" value="<?php echo (int) $link->value; ?>"<?php echo $selected ? ' checked="checked"' : ''; ?> />
<label for="<?php echo $id . $link->value; ?>" class="pull-left"><?php echo $link->text; ?> <span class="small"><?php echo JText::sprintf('JGLOBAL_LIST_ALIAS', $this->escape($link->alias));?></span></label>
</div>
<?php
if (!isset($type->links[$i + 1]))
{
echo str_repeat('</li></ul>', $link->level);
}
$prevlevel = $link->level;
?>
<?php endforeach; ?>
</li>
<?php endif; ?>
<?php endforeach; ?>
</ul>
Here is the function which creates the Query.
public static function getMenuLinks($menuType = null, $parentId = 0, $mode = 0, $published = array(), $languages = array())
{
$db = JFactory::getDbo();
$query = $db->getQuery(true)
->select('a.id AS value, a.title AS text, a.alias, a.level, a.menutype, a.type, a.template_style_id, a.checked_out')
->from('#__menu AS a')
->join('LEFT', $db->quoteName('#__menu') . ' AS b ON a.lft > b.lft AND a.rgt < b.rgt');
// Filter by the type
if ($menuType)
{
$query->where('(a.menutype = ' . $db->quote($menuType) . ' OR a.parent_id = 0)');
}
if ($parentId)
{
if ($mode == 2)
{
// Prevent the parent and children from showing.
$query->join('LEFT', '#__menu AS p ON p.id = ' . (int) $parentId)
->where('(a.lft <= p.lft OR a.rgt >= p.rgt)');
}
}
if (!empty($languages))
{
if (is_array($languages))
{
$languages = '(' . implode(',', array_map(array($db, 'quote'), $languages)) . ')';
}
$query->where('a.language IN ' . $languages);
}
if (!empty($published))
{
if (is_array($published))
{
$published = '(' . implode(',', $published) . ')';
}
$query->where('a.published IN ' . $published);
}
$query->where('a.published != -2')
->group('a.id, a.title, a.alias, a.level, a.menutype, a.type, a.template_style_id, a.checked_out, a.lft')
->order('a.lft ASC');
// Get the options.
$db->setQuery($query);
try
{
$links = $db->loadObjectList();
}
catch (RuntimeException $e)
{
JError::raiseWarning(500, $e->getMessage());
return false;
}
if (empty($menuType))
{
// If the menutype is empty, group the items by menutype.
$query->clear()
->select('*')
->from('#__menu_types')
->where('menutype <> ' . $db->quote(''))
->order('title, menutype');
$db->setQuery($query);
try
{
$menuTypes = $db->loadObjectList();
}
catch (RuntimeException $e)
{
JError::raiseWarning(500, $e->getMessage());
return false;
}
// Create a reverse lookup and aggregate the links.
$rlu = array();
foreach ($menuTypes as &$type)
{
$rlu[$type->menutype] = & $type;
$type->links = array();
}
// Loop through the list of menu links.
foreach ($links as &$link)
{
if (isset($rlu[$link->menutype]))
{
$rlu[$link->menutype]->links[] = & $link;
// Cleanup garbage.
unset($link->menutype);
}
}
return $menuTypes;
}
else
{
return $links;
}
You can simply remove the join. I'm pretty sure the join has absolutely no effect in your query, and it will be a lot quicker. You can try to run the query directly in your database with and without the join, to verify that the result is the same.
I'm not sure what this join was intended to do, but i guess it is some remnant of some functionality the programmer was trying to achieve, but that was realized differently or dropped, leaving a useless join.
The structure of this kind of hierarchical table is like this to prevent these sort of join. You have a lft and a rgt value, and any item that is between the lft and the rgt is a sub-item. In addition you have a level-value, telling you how deep in the tree a value is. So to select all children of an item, you can do:
select * where lft>item.lft and rgt>item.rgt
To select only direct descendants of your item, do
select * where lft>item.lft and rgt>item.rgt and level=item.level+1
The structure in the database is a little hard to maintain, requiring special functions to update the data, but it is quick to search and extract data.
So, your getMenuLinks() - function should start like
public static function getMenuLinks($menuType = null, $parentId = 0,
$mode = 0, $published = array(), $languages = array())
{
$db = JFactory::getDbo();
$query = $db->getQuery(true)
->select('a.id AS value, a.title AS text, a.alias, a.level,
a.menutype, a.type, a.template_style_id, a.checked_out')
->from('#__menu AS a');
// Filter by the type
if ($menuType)
...

PHP foreach only in if statement

I have this code that is working:
$productID = $_POST['productID'];
$sql_product="SELECT * FROM cc_menu_customizations WHERE cust_asoc='$productID'";
$stmt_product = $conn->prepare($sql_product);
$stmt_product->execute();
$result_product = $stmt_product->setFetchMode(PDO::FETCH_ASSOC);
if($result_product > 0) {
while($row = $stmt_product->fetch()) {
$menuArr[$row['cust_title']][] = '<li class="item-inmodal-extra-wrap-options"><p>'. $row['cust_desc'] .'<p></li>';
}
foreach($menuArr as $menuTitle => $productArr) {
echo '<div class="item-inmodal-extra"><h3>'. $menuTitle .'</h3><ul class="item-inmodal-extra-wrap">';
foreach($productArr as $key =>$productname) {
echo $productname;
}
echo '</ul></div>';
}
}
Sometimes the query will find results on $productID and sometimes no. But I don't know why if the query doesn't find results apache still send me error about the variable $menuArrin foreach doesn't exist...
shouldn't this variable only be active if the if statement is true?
EDIT
Final result... better?
$productID = $_POST['productID'];
$sql_product = "SELECT * FROM cc_menu_customizations WHERE cust_asoc= ?";
$stmt_product = $conn->prepare($sql_product);
$sql_count="SELECT count(*) FROM cc_menu_customizations WHERE cust_asoc='$productID'";
$countResult = $conn->query($sql_count);
if($countResult->fetchColumn() > 0) {
$stmt_product->bindParam(':cust_asoc', $productID);
$stmt_product->execute(array($productID));
$stmt_product->setFetchMode(PDO::FETCH_ASSOC);
while($row = $stmt_product->fetch()) {
$menuArr[$row['cust_title']][] = '<li class="item-inmodal-extra-wrap-options"><p>'. $row['cust_desc'] .'<p></li>';
}
foreach($menuArr as $menuTitle => $productArr) {
echo '<div class="item-inmodal-extra"><h3>'. $menuTitle .'</h3><ul class="item-inmodal-extra-wrap">';
foreach($productArr as $key =>$productname) {
echo $productname;
}
echo '</ul></div>';
}
}
echo '<div class="item-inmodal-extra">
<h3>Special Instructions</h3>
<textarea class="item-inmodal-extra s-intructions" placeholder="Please explicitly state any allergies you have. Requests incurring additional cost are fulfilled at merchant's discretion"></textarea>
</div>';
Security issues aside, the answer to your question below. Your commenters are correct, you should use bound parameters and do all appropriate sanitization but that is another question all together.
Should be:
<?php
$productID = $_POST['productID'];
$sql_product="SELECT * FROM cc_menu_customizations WHERE cust_asoc='$productID'";
$sql_count="SELECT count(*) FROM cc_menu_customizations WHERE cust_asoc='$productID'";
$countResult = $conn->query($sql_count)
if($countResult->fetchColumn() > 0) {
$stmt_product = $conn->prepare($sql_product);
$stmt_product->execute();
$result_product = $stmt_product->setFetchMode(PDO::FETCH_ASSOC);
while($row = $stmt_product->fetch()) {
$menuArr[$row['cust_title']][] = '<li class="item-inmodal-extra-wrap-options"><p>'. $row['cust_desc'] .'<p></li>';
}
foreach($menuArr as $menuTitle => $productArr) {
echo '<div class="item-inmodal-extra"><h3>'. $menuTitle .'</h3><ul class="item-inmodal-extra-wrap">';
foreach($productArr as $key =>$productname) {
echo $productname;
}
echo '</ul></div>';
}
}
PDOStatement::rowCount
For most databases, PDOStatement::rowCount() does not return the number of rows affected by a SELECT statement. Instead, use PDO::query() to issue a SELECT COUNT(*) statement with the same predicates as your intended SELECT statement, then use PDOStatement::fetchColumn() to retrieve the number of rows that will be returned. Your application can then perform the correct action.

Echo return mulitiple variables

I have a problem with an mysql query, I need to extract all data from my table and use him as another sql query.
This is the code I am using:
<?php
function toateMhz() {
require ('SQL.php');
$sql = "SELECT DISTINCT(performanta_cpu) FROM modele ORDER BY CAST(performanta_cpu AS UNSIGNED) DESC";
foreach ($dbh->query($sql) as $linie)
{
$mhz[] = $linie['performanta_cpu'];
}
if(isset($mhz['1']))
{
$mhz1 = "$mhz[0] OR ";
}
else $mhz['0'];
if(isset($mhz['2']))
{
$mhz2 = "$mhz[1] OR ";
}
else $mhz['1'];
if(isset($mhz['3']))
{
$mhz3 = "$mhz[2] OR ";
}
else $mhz['2'];
if(isset($mhz['4']))
{
$mhz4 = "$mhz[3] OR ";
}
else $mhz['3'];
if(isset($mhz['5']))
{
$mhz5 = "$mhz[4] OR ";
}
else $mhz['4'];
if(isset($mhz['6']))
{
$mhz6 = "$mhz[5] OR ";
}
else $mhz['5'];
if(isset($mhz['7']))
{
$mhz7 = "$mhz[6] OR ";
}
else $mhz['6'];
if(isset($mhz['8']))
{
$mhz8 = "$mhz[7] OR ";
}
else $mhz['7'];
if(isset($mhz['9']))
{
$mhz9 = "$mhz[8] OR ";
}
else $mhz['8'];
if(isset($mhz['10']))
{
$mhz10 = "$mhz[9] OR ";
}
else $mhz['9'];
if(isset($mhz['11']))
{
$mhz11 = "$mhz[10] OR ";
}
else $mhz['10'];
if(isset($mhz['12']))
{
$mhz12 = "$mhz[11] OR ";
}
else $mhz['11'];
if(isset($mhz['13']))
{
$mhz13 = "$mhz[12] OR ";
}
else $mhz['12'];
if(isset($mhz['14']))
{
$mhz14 = "$mhz[13] OR ";
}
else $mhz['13'];
if(isset($mhz['15']))
{
$mhz14 = "$mhz[14] OR ";
}
else $mhz['14'];
$frecvente = "$mhz1 $mhz2 $mhz3 $mhz4 $mhz5 $mhz6 $mhz7 $mhz8 $mhz9 $mhz10 $mhz11 $mhz12 $mhz13 $mhz14";
return $frecvente;
}
echo toateMhz();
?>
And this is the result from code:
2000 OR 1600 OR 1500 OR 1400 OR 1000 OR 800 OR
But the correct result is 2000 OR 1600 OR 1500 OR 1400 OR 1000 OR 800 OR 200
Last word must not be OR
Not quite sure but this might do the trick
foreach ($dbh->query($sql) as $linie) {
// append value of this record to the array $mhz
$mhz[] = $linie['performanta_cpu'];
}
// return the concatenation of all elements in $mhz with ' OR ' as "glue" between elements
return join(' OR ', $mhz);
join($s, $arr) is an alias of implode($s, $arr) which concatenates all (string) elements of the given array $arr and putting $s "between" the elements. E.g.
$x = array('a','b', 'c');
echo join(' - ', $x);
prints a - b - c
Use implode to join your array values into a string :
function toateMhz() {
require ('SQL.php');
$sql = "SELECT DISTINCT(performanta_cpu) FROM modele ORDER BY CAST(performanta_cpu AS UNSIGNED) DESC";
foreach ($dbh->query($sql) as $linie)
{
$mhz[] = $linie['performanta_cpu'];
}
return implode(" OR ", $mzh);
}
echo toateMhz();

Categories