Count filled SQL array fields PHP - php

I´m fetching an array from a mysql query like this.
$viewerSQL = mysql_query("SELECT * FROM `this` WHERE id = ".
mysql_real_escape_string($_GET[id]) ."");
$pageData = mysql_fetch_array($pageSql);
I get an array with like 40 entries, i want to check seven of them by name if they are filled.
What i´ve tried and what I thought about so far:
$oioi = 0;
while($oioi<7){
$oioi++;
$pic = "pic".$oioi;
$active="";
$path = "./upload/objectoffers/$viewerData[id]/$pic";
$picDesc = "pic".$oi."Desc";
$picArray = '$viewerData['.$pic.']';
echo $pic."<br>";
echo $picArray."<p>";
if(!empty($path)){
if($oioi==1){$active = "active";}?>
<div class="item <?=$active;?>">
<img style="width: 100%;" src="./images/<?=$viewerData[$pic];?>" alt="<?=$viewerData[$picDesc]?>">
</div>
<?
}}
?>
But this doesn´t work because: $path is NEVER empty...I wanted to avoid to write "if(!empty)" for every single $viewerData[pic1] to $viewerData[pic7] array manual...
that´s why i´m here...
maybe you can help me improving this or offer some tips.
Thanks!
edit: This is what I get as "output":
pic1
$viewerData[pic1]
pic2
$viewerData[pic2]
pic3
$viewerData[pic3]
pic4
$viewerData[pic4]
pic5
$viewerData[pic5]
pic6
$viewerData[pic6]
pic7
$viewerData[pic7]

I think you should use file_exists instead !empty:
$oioi = 0;
while ($oioi < 7) {
$oioi++;
$pic = "pic" . $oioi;
$active = "";
$path = "./upload/objectoffers/$viewerData[id]/$pic";
$picDesc = "pic" . $oi . "Desc";
$picArray = '$viewerData[' . $pic . ']';
echo $pic . "<br>";
echo $picArray . "<p>";
if (file_exists($path)) {
if ($oioi == 1) {
$active = "active";
}
?>
<div class="item <?= $active; ?>">
<img style="width: 100%;" src="./images/<?= $viewerData[$pic]; ?>" alt="<?= $viewerData[$picDesc] ?>">
</div>
<?php
}
}

Related

How to give 3 different color for div's in loop in php

Trying to give 3 different color for div's in loop in php, now its working only two .how can i impliment alternative color for div.? Here what I want.
style
.redBackground { background-color:#F00; }
.blueBackground { background-color:#03F;}
.greenBackground { background-color:#6F3; }
php
<?php
$new= mysql_query("select * from tbl_news");
while ($row=mysql_fetch_array($new))
{
$x++;
$class = ($x%2 == 0)? 'redBackground': 'blueBackground' ;
echo "<tr class='$class'>";
$id = $row['id'];
$news = $row['news'];
?>
<div class="col-md-2 col-sm-12 col-xs-12 news_main_div">
<div class="md-trigger" data-modal="modal-11">
<div <?php echo "<tr class='$class'> ";?>>
<h1 style=" margin-bottom:5px;">
<strong ><?php echo $news ?></strong>
</h1></div></div><?php } ?>
Use color array like below
$color_array = array('whiteBackground', 'grayBackground', 'blueBackground');
$x=0;
while($row=mysql_fetch_array($new)){
$x++;
$class = $color_array[$x%3];
}
And in future, if you want to more color, then simply add color-class in array and change in $color_arrar[$x%n], where n=number_of_color
If you want random color, then use below code
$color_arrar = array('whiteBackground ','grayBackground ','blueBackground ');
$size_of_array = sizeof($color_arrar);
while($row=mysql_fetch_array($new)){
$n = rand(0,$size_of_array-1);
$class = $color_arrar[$n%3];
}
Please try this
if($x%3 == 0)
$class = 'greenBackground';
else if($x%2 == 0 )
$class = 'redBackground';
else
$class = 'blueBackground';
If you need it in random order you can use array_rand function
$color = array("redBackground", "blueBackground", "greenBackground");
$colorValue = array_rand($color, 1);
$class = $color [$colorValue];

Using a function to query a database

I have a page and I would really like some help / advice to create a better way / function to call in information from another table.
At the moment, my code looks like:
[I do know this is deprecated SQL and would really like to do some nice SQLi for this.]
<?
$menuid = "100";
$imageid = "50";
// ** Talk to 'imagedirectory' table
mysql_select_db($database_db, $BASEdb);
$query_displayimage = "SELECT * FROM imagedirectory WHERE menuid = ".$menuid." AND imageid = ".$imageid."";
$displayimage = mysql_query($query_displayimage, $BASEdb) or die(mysql_error());
$row_displayimage= mysql_fetch_assoc($displayimage);
?>
<img src="/images/assets/<?php echo $menuid; ?>-<?php echo $imageid; ?>-<?php echo $row_displayimage['urlslug']; ?>.jpg" alt="<?php echo $row_displayimage['alttext']; ?>" />
I figure There really has to be a better way because if there is 10 images on a page, this is pretty intense way of doing it.
Since you seem to know that mysql_* is deprecated, I am assuming you have read up on, and are using mysqli_* instead.
You needn't query the database every time. mysqli_query() returns a mysqli_result, which you can iterate over, and read using functions like mysqli_fetch_assoc(). Here is one way of doing it:
<?php
// store your query in a variable.
$query_displayimage = "SELECT * FROM imagedirectory";
// query the database.
$displayimage = mysqli_query($query_displayimage, $BASEdb);
// check for errors.
$dbErrors = mysqli_error($BASEdb);
if (count($dbErrors))
{
print_r($dbErrors);
die();
}
// iterate over the returned resource.
while ($row_displayimage = mysql_fetch_assoc($displayimage))
{
echo '<img src="/images/assets/' . $menuid . '-' . $imageid . '-' . $row_displayimage['urlslug'] . '.jpg" alt="' . $row_displayimage['alttext'] . '" />';
}
?>
Hope that helped.
EDIT:
You can use this code in a function, too. For example:
<?php
function printImage($menuid, $imageid)
{
$query_displayimage = "SELECT * FROM imagedirectory";
$displayimage = mysqli_query($query_displayimage, $BASEdb);
$dbErrors = mysqli_error($BASEdb);
if (count($dbErrors))
{
print_r($dbErrors);
die();
}
if ($row_displayimage = mysql_fetch_assoc($displayimage))
{
echo '<img src="/images/assets/' . $menuid . '-' . $imageid . '-' . $row_displayimage['urlslug'] . '.jpg" alt="' . $row_displayimage['alttext'] . '" />';
}
else // if there is a problem getting the image
{
echo 'Error getting image.';
}
}
?>
and elsewhere in your HTML, you would do something like:
<div>
And here is an image!
<?php printImage(20, 50); ?>
</div>

In template page_list get image attribute Concrete5

My following code is based on
1.Get current URL
2.Go through array and check if in url value = to value in array
do this:
$on_this_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
foreach ($city_array as $sandwich) {
if (strpos($on_this_link, $sandwich) == true) {
$sandwich = trim($sandwich, '/');
$city = $sandwich;
if ($city == 'newyork') {
foreach ($category_array as $double_sandwich) {
if (strpos($on_this_link, $double_sandwich) == true) {
$double_sandwich = trim($double_sandwich, '/');
$category_is = $double_sandwich;
Loader::model('page_list');
$nh = Loader::helper('navigation');
$pl = new PageList();
$pl->filterByAttribute('city', '%' . $city . '%', 'like');
$pl->filterByAttribute('category','%'.$category_is.'%','like');
$pl->sortByDisplayOrder();
$pagelist = $pl->get();
foreach ($pagelist as $p) {
echo '<li> ' .htmlspecialchars($p->getCollectionName()) . ' </li>';
?>
}
}
}
}
So It will show me only pages that have the same attribute with URL
Each of this page has image attribute that I want to show.
How can I pass this Image Attribute??
Check out the comments in the page list block's view template:
https://github.com/concrete5/concrete5/blob/master/web/concrete/blocks/page_list/view.php#L33
You can get image attributes by putting some code like this inside your foreach ($pagelist as $p) loop:
$img = $p->getAttribute('example_image_attribute_handle');
if ($img) {
//you could output the original image at its full size like so:
echo '<img src="' . $img->getRelativePath() . '" width="' . $img->getAttribute('width') . '" height="' . $img->getAttribute('height') . '" alt="" />';
//or you could reduce the size of the original and output that like so:
$thumb = Loader::helper('image')->getThumbnail($img, 200, 100, false); //<--200 is width, 100 is height, and false is for cropping (change to true if you want to crop the image instead of resize proportionally)
echo '<img src="' . $thumb->src . '" width="' . $thumb->width . '" height="' . $thumb->height . '" alt="" />';
}
Thx but I did it already just another way!
I didnt used
Loader::model('page_list');
Instead I used:
$blockType = BlockType::getByHandle('page_list');
And hardcoded the block!
$th = Loader::helper('text');
$ih = Loader::helper('image');
$page_current = Page::getCurrentPage();
$page_2 = $page_current->getCollectionHandle();
$img = $page->getAttribute('product'); $thumb =
$ih->getThumbnail($img, 240,150, false);
And after I changed a little bit my Code above:
$on_this_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
foreach ($city_array as $sandwich) {
if (strpos($on_this_link, $sandwich) == true) {
$sandwich = trim($sandwich, '/');
$city = $sandwich;
if ($city == 'newyork') {
foreach ($category_array as $double_sandwich) {
if (strpos($on_this_link, $double_sandwich) == true) {
$double_sandwich = trim($double_sandwich, '/');
$category_is = $double_sandwich;
$city_att = $page->getAttribute('city', '%' . $city . '%', 'like');
$sub_cat_att = $page->getAttribute('category','%'.$category_is.'%','like'); ?>
<?php if($city == $city_att && $category_is == $sub_cat_att){ ?><li><img src="<?php echo $thumb->src ?>" width="<?php echo $thumb->width ?>" height="<?php echo $thumb->height ?>" alt="" />
<h3> <?php echo $title ?></h3>
<div class="product_description">
<?php echo $description ?>
</div>
Read More...
</li> <?php } ?> <?php
}
}
}
So everything it is working But still thx for respond! Apreciate

PHP Search: Using Jquery to alter a php a value

I have a comics website. A feature it has is to allow users to search comics... the search will instantly parse the input and return thumbnail results based on matching title and keywords.
Originally, the search would return all of the results, and the bounding search box would expand infinitely downward, holding every single comic result. I thought it may be a nice touch to limit the results to 4, and display a message like "load 5 remaining images" if the user chooses to do so.
If they click on that message, I wanted limiting php variable to be removed or changed.
So far, it loads with the limit, and shows a link...
EDIT: Latest Code:
search_field.php (the search file that get's included on a page... this file calls search.php via JQuery):
<?php $site = (isset($_GET['site']) ? ($_GET['site']) : null); ?>
<div id="sidebar" class="searchborder">
<!--Allow users to search for comic-->
<!--<span class="search">Search for <?php// echo (($site == "artwork") ? 'artwork' : 'a comic'); ?> </span>-->
<script type="text/javascript">
function GetSearch(mySearchString){
$.get("./scripts/search.php", {_input : mySearchString, _site : '<?php echo $site ?>'},
function(returned_data) {
$("#output").html(returned_data);
}
);
}
</script>
<center>
<table>
<tr>
<td>
<span class="search">
<img src="./images/SiteDesign/Search.png" />
<input type="text" onkeyup="GetSearch(this.value)" name="input" value="" />
<!--<input id="site" type="hidden" value="<?php// echo $site; ?>">-->
</span>
</td>
</tr>
</table>
</center>
<span id="output"> </span>
</div>
search.php, the file that's called to parse the string and return the results:
<?php
//Query all images:
include 'dbconnect.php';
$site = $_GET['_site'];
$input = (isset($_GET['_input']) ? ($_GET['_input']) : 0);
$siteChoice = (isset($_GET['_choice']) ? ($_GET['_choice']) : $site);
$start = (isset($_GET['_start']) ? ($_GET['_start']) : null);
echo "start: " . $start;
//if user goes to hittingtreeswithsticks.com... no "site" value will be set... so I need to set one
if ($site == null) {
$site = "comics";
}
if ($siteChoice == "artwork") {
$sql = "SELECT id, title, keywords, thumb FROM artwork";
$thumbpath = "./images/Artwork/ArtThumbnails/";
}
else if ($siteChoice == "comics") {
$sql = "SELECT id, title, keywords, thumb FROM comics";
$thumbpath = "./images/Comics/ComicThumbnails/";
}
else {
$sql = "SELECT id, title, keywords, thumb FROM $site";
if ($site == "artwork") {
$thumbpath = "./images/Artwork/ArtThumbnails/";
}
else {
$thumbpath = "./images/Comics/ComicThumbnails/";
}
}
/* For this to work, need all comics replicated in an "All Comics" file along with "All Thumbnails"
else {
$sql = "SELECT id, title, thumb FROM comics
UNION
SELECT id, title, thumb FROM artwork";
$thumbpath = "./images/AllThumbnails/";
}*/
$imgpaths = $mysqli->query($sql);
mysqli_close($mysqli);
$idresult = array();
$imgresult = array();
$thumbresult = array();
//CHECK IF $INPUT == IMAGE PATH
if (strlen($input) > 0)
{
while ($row = $imgpaths->fetch_assoc())
{
//query against key words, not the image title (no one will remember the title)
if (stripos($row['keywords'], $input) !== false || strtolower($input)==strtolower(substr($row['title'],0,strlen($input))))
//if (strtolower($input)==strtolower(substr($row['title'],0,strlen($input))))
{
array_push($idresult, $row['id']);
array_push($imgresult, $row['title']);
array_push($thumbresult, $row['thumb']);
}
}
//ECHO RESULTS ARRAY
if(count($imgresult) == 0)
{
echo "<p>no suggestions</p>";
}
else
{
echo "<ul>";
$k = 0;
$max = 4;
if (count($imgresult) > $max) {
while ($k < count($imgresult) && $k < $max)
{
echo '<li>
<span class="sidebarimages"><a href=".?action=viewimage&site=' . $siteChoice . '&id=' . $idresult[$k] . '">
<img src="./scripts/thumber.php?img=.'.$thumbpath.$thumbresult[$k].'&mw=90&mh=90"/></a></span>
</li>';
$k++;
}
$difference = count($imgresult)-$k;
echo "<br/><i><a href='.?action=homepage&site=" . $siteChoice . "&start=4' class='loadSearch'>load " . $difference . " more result" . (($difference != 1) ? 's' : '') . "... </a></i>";
}
else {
while ($k < count($imgresult))
{
echo '<li>
<span class="sidebarimages"><a href=".?action=viewimage&site=' . $siteChoice . '&id=' . $idresult[$k] . '">
<img src="./scripts/thumber.php?img=.'.$thumbpath.$thumbresult[$k].'&mw=90&mh=90"/></a></span>
</li>';
$k++;
}
}
echo "</ul>";
}
}
?>
<script type="text/javascript">
$(".loadSearch").click(function() {
//alert("Test");
$.get("./search.php", {_start : 4},
function (returned_data) {
$("#moreResults").html(returned_data);
}
);
});
</script>
Try this:
<script type="text/javascript">
$("#loadSearch").click(function() {
$.get('URL WITH QUERY', function(data) {
$('#results').html(data);
});
});
</script>
From what i get all you need is when "load more" is clicked only new results should be shown.
Load more has to be a url same as your search url.
Search/Autocomplete URL - example.com/autocomplete?q=xkd
Load More URL - example.com/autocomplete?q=xkd&start=4&max=1000
Just add two parameters to your url. start and max. Pass them to your queries and you get exact result.
Only verify Start < Max and are integers intval() and not 0 empty(). Also if Max <= 4 then dont show load more.
I would give all of your results back, then try to determine your results. If more then 4, loop out the first 4 results. If the user clicks on the load more button your start looping from your 4th element. That way you only need to hit the server once (per search).
Try to give back your results in json, so you can format it the way you like in your html file.
In pseudo code:
searchTerm = 'hello';
resultsFromServer = getResults($searchterm);
resultcounter = count(resultsFromServer);
if(resultcounter > 4)
loop 4 results
else
loop all results
$(".loadSearch").click(function(e) {
//alert("Test");
e.preventDefault();
$.get("./search.php", {_start : 4},
function (returned_data) {
$("#moreResults").html(returned_data);
}
);
I ended up going with jquery show and hide functions.
PHP Snippet:
//ECHO RESULTS ARRAY
if(count($imgresult) == 0)
{
echo "<p>no suggestions</p>";
}
else
{
echo "<ul>";
$k = 0;
$max = 4;
while ($k < count($imgresult) && $k < $max)
{
echo '<li>
<span class="sidebarimages"><a href=".?action=viewimage&site=' . $siteChoice . '&id=' . $idresult[$k] . '">
<img src="./scripts/thumber.php?img=.'.$thumbpath.$thumbresult[$k].'&mw=90&mh=90"/></a></span>
</li>';
$k++;
}
$difference = count($imgresult)-$k;
echo '<div id="moreResults">';
while ($k < count($imgresult))
{
echo '<li>
<span class="sidebarimages"><a href=".?action=viewimage&site=' . $siteChoice . '&id=' . $idresult[$k] . '">
<img src="./scripts/thumber.php?img=.'.$thumbpath.$thumbresult[$k].'&mw=90&mh=90"/></a></span>
</li>';
$k++;
}
echo '</div>';
if (count($imgresult) > $max) {
?>
<br />Load <?php echo $difference; ?> more result<?php echo (($difference != 1) ? 's' : ''); ?>...
<?php
}
echo "</ul>";
}
}
Jquery:
<script type="text/javascript">
$("#moreResults").hide();
$("#showMore").click(function() {
$("#moreResults").show();
$("#showMore").hide();
});

PHP Dynamic Count & Limit Menu items

I want to modify this code which works pretty good but (or I don't know because I'm new with php) I can't limit the number of li's displayed for the main elements in the menu. The actual code will echo all elements it finds, I want to limit the times
<li><a href='{$sLink}' {$sOnclick} target='_parent'>{$sPictureRep}{$sText}</a>
this line is echoed.. let's say to echo just the first 15 elements + a "MORE" button under which to display the rest of the elements as sub-menus.. (this is a 2 level horizontal menu). Can someone please help me? I really tried a lot but I'm not an expert in PHP..
Thanks!
<?php
require_once( '../../../inc/header.inc.php' );
require_once( DIRECTORY_PATH_INC . 'membership_levels.inc.php' );
require_once( DIRECTORY_PATH_ROOT . "templates/tmpl_{$tmpl}/scripts/TemplMenu.php" );
class SimpleMenu extends TemplMenu
{
function getCode()
{
$this->iElementsCntInLine = 100;
$this->getMenuInfo();
$this->genTopItems();
return $this->sCode;
}
function genTopItem($sText, $sLink, $sTarget, $sOnclick, $bActive, $iItemID, $isBold = false, $sPicture = '')
{
$sActiveStyle = ($bActive) ? ' id="tm_active"' : '';
if (!$bActive) {
$sAlt= $sOnclick ? ( ' alt="' . $sOnclick . '"' ) : '';
$sTarget = $sTarget ? ( ' target="_parent"' ) : '';
}
$sLink = (strpos($sLink, 'http://') === false && !strlen($sOnclick)) ? $this->sSiteUrl . $sLink : $sLink;
$sSubMenu = $this->getAllSubMenus($iItemID);
$sImgTabStyle = $sPictureRep = '';
if ($isBold && $sPicture != '') {
$sPicturePath = getTemplateIcon($sPicture);
$sPictureRep = "<img src='{$sPicturePath}' style='vertical-align:middle;width:16px;height:16px;' />";
$sText = ' ';
$sImgTabStyle = 'style="width:38px;"';
}
$sMainSubs = ($sSubMenu=='') ? '' : " {$sSubMenu} </a>";
$this->sCode .= "
<li><a href='{$sLink}' {$sOnclick} target='_parent'>{$sPictureRep}{$sText}</a>
<div id='submenu'>
<ul>
<li>{$sMainSubs}</li>
</ul>
</div>
</li>
";
}
}
$objMenu = new SimpleMenu();
echo "<ul id='ddmenu'>";
echo $objMenu->getCode();
echo "</ul>";
?>
It's difficult to tell exactly where you want to do this in your code, but I figure you're looking for something like:
<?php
for ($i = 0; i < 15; i ++){
echo "<li><a href='{$sLink}' {$sOnclick} target='_parent'>{$sPictureRep}{$sText}</a>"
}
echo "<li><a href='more' target='_parent'>More...</a>"
?>

Categories